Text to XML using Node.js in Switch Scripter

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

Text to XML using Node.js in Switch Scripter

Post by mrkkrai » Mon Jan 18, 2021 10:58 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.xml output:
<tags>
<ShippedVia>Purolator Edmonton</ShippedVia>
<TrackingID>607431612227</TrackingID>
<PO>PO # : 9197</PO>
</tags>

Thanks

foxpalace
Member
Posts: 23
Joined: Fri Jan 14, 2011 12:25 pm

Re: Text to XML using Node.js in Switch Scripter

Post by foxpalace » Tue Jan 19, 2021 1:54 pm

Hi,
has your inputfile always the same structure?

foxpalace
Member
Posts: 23
Joined: Fri Jan 14, 2011 12:25 pm

Re: Text to XML using Node.js in Switch Scripter

Post by foxpalace » Tue Jan 19, 2021 2:23 pm

Hi,
I need in short a similar Script and I have to learn more TypeScript. So I think this is rudimentary, but it did what you need

Code: Select all

import fs from "fs";

async function jobArrived(s: Switch, flowElement: FlowElement, job: Job) {

    let dateiname = await job.getName();
    let dateipfad = await job.get(AccessLevel.ReadOnly);
    let tempfile = "/tmp/tmp.xml"; // you can read the inputfile and put it here

    // read the file
    try {
        var array = fs.readFileSync(dateipfad, { encoding: "utf8" }).toString().split("\n");
    } catch(error) {
        await job.log(LogLevel.Error, "We could'nt read the File " + dateiname);
    }

    // we know how much ARRAYs are here, because the Textfile has always the same lines
    fs.writeFileSync(tempfile, '<tags>\n');
    fs.appendFileSync(tempfile, '<ShippedVia>' + array[6] + '</ShippedVia>\n')
    fs.appendFileSync(tempfile, '<TrackingID>' + array[8] + '</TrackingID>\n')
    fs.appendFileSync(tempfile, '<PO>' + array[9] + '</PO>\n')
    fs.appendFileSync(tempfile, '</tags>')

    // we don't need the old txt-file
    await job.sendToNull();
    // we create an other job
    const xmljob = await job.createChild(tempfile);
	//send to outfolder
    await xmljob.sendToSingle();
    // delete tmpfile
    fs.unlinkSync(tempfile);

}


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

Re: Text to XML using Node.js in Switch Scripter

Post by mrkkrai » Sat Jan 23, 2021 7:50 am

Hi:

Yes. The input file has always the same structure. I tried the script in SwitchScripter but it returns error. Please see the screenshot.

Image

https://ibb.co/zhRwnkw

foxpalace
Member
Posts: 23
Joined: Fri Jan 14, 2011 12:25 pm

Re: Text to XML using Node.js in Switch Scripter

Post by foxpalace » Mon Jan 25, 2021 2:15 pm

Hi,
yes, because you use legacy Script and not TypeScript.
Greetings
Michael

Post Reply