Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML with Typescript and xml2js

I am trying to work with Express and parse an XML body. I am using the bodyparser for text, but cannot get the xml2js to parse my XML into a usable format.

import * as xml2js from 'xml2js';
try {
    const XML:string = '<Pan>0000000000000702203</Pan>';

    xml2js.parseString(XML, {trim: true}, function (err, result) {
        if(err) console.log(err);
        console.log(result); 
    });
} catch (e) {
    console.log(e);
}

either does not work:

try {
    xml2js.parseString(XML, {trim: true}, (err, result) => {
        if(err) console.log(err);
        console.log(result); 
    });
} catch (e) {
    console.log(e);
}

When running this in the VSCode debugger and the code immediate skips over the function and does not process the xml2js.parseString(). err and result never get values.

I have also tried with it using the Parser() class:

const p:xml2js.Parser = new xml2js.Parser();
p.parseString(XML, (err:{}, result:{}) => {
    if(err) console.log(err);
    console.log(result); 
});

p.parseString(XML, function(err:{}, result:{}) {
    if(err) console.log(err);
    console.log(result); 
});

This does the same thing and does not work or populate the err,result.

Update: 2018/10/11: I have tried debuging this, and it appears the sax.parser is working and returning data. I have done the following:

console.log(xml2js.parseString(XML, (err, result) => {
    if (err) {
        console.log(err);
    }
});

and I do get the SaxParser returned as an object in VSCode which I can interrogate and see my results in, but I do not get my callback function called.

Debug:

SAXParser {comment: "", sgmlDecl: "", textNode: "", tagName: "", doctype: "", …}

The xml2js.parseString though is supposed to not return anything, as the definition has this as a void.

like image 846
Steven Scott Avatar asked Oct 29 '22 03:10

Steven Scott


1 Answers

import xml2js from 'xml2js';

async parseXml(xmlString: string) {
    return await new Promise((resolve, reject) => xml2js.parseString(xmlString, (err, jsonData) => {
      if (err) {
        reject(err);
      }
      resolve(jsonData);
    }));
like image 177
Shrikant656 Avatar answered Nov 15 '22 07:11

Shrikant656