Text to XML in Switch Scripter

Post Reply
mrkkrai
Member
Posts: 27
Joined: Thu Mar 17, 2016 4:31 pm

Text to XML in Switch Scripter

Post by mrkkrai » Mon Jan 18, 2021 7:08 am

Hi:

Please help me to convert text file to xml using Switch Scripter:

Job1.txt input:

500 LABEL
500
1 1.72 500
1 1.72
21 01 04 HARDING'S SERVICES
Shipped Via :
Purolator Edmonton
Tracking # :
607431612227
PO # : 9197
L 1612296

Job1.txt output:

<tag>500 LABEL</tag>
<tag>500</tag>
<tag>1 1.72 500</tag>
<tag>1 1.72</tag>
<tag>21 01 04 HARDING'S SERVICES</tag>
<tag>Shipped Via :</tag>
<tag>Purolator Edmonton</tag>
<tag>Tracking # :</tag>
<tag>607431612227</tag>
<tag>PO # : 9197</tag>
<tag>L 1612296</tag>

Thanks

freddyp
Advanced member
Posts: 576
Joined: Thu Feb 09, 2012 3:53 pm

Re: Text to XML in Switch Scripter

Post by freddyp » Mon Jan 18, 2021 9:20 am

A word of advice: do not do this using legacy scripting, use NodeJS instead. It may take you a bit longer to get started, but in the long term it will bring you more benefits.

There are packages to convert JS objects to XML (e.g. json2xml). In other words, read the text file and place the info into a JS object and then dump that object into an xml file using the package.

Warning: your XML is not valid. An XML file must have 1, and only 1, root node. This is valid XML:

Code: Select all

<tags>
    <tag>500 LABEL</tag>
    <tag>500</tag>
    ...
</tags>
Another word of advice: instead of placing every line into a <tag> element, add some intelligence so instead of

Code: Select all

<tag>Tracking # :</tag>
<tag>607431612227</tag>
you get

Code: Select all

<trackingcode>607431612227</trackingcode>
That makes it easier afterwards to extract the desired information from the XML.

Post Reply