This is my XML
<?xml version="1.0" encoding="UTF-8"?>
<message>
<return>
<BYTES_LENGTH>12019</BYTES_LENGTH>
<STATUS>DONE</STATUS>
</return>
<return>
<BYTES_LENGTH>1129</BYTES_LENGTH>
<STATUS>DONE</STATUS>
<ERROR_CODE>NO MESSAGE FOUND</ERROR_CODE>
</return>
</message>
I am writing a logic in Node JS using xml2js-xpath library to extract ERROR_CODES and STATUS values in array using the following code -
var xml2js = require("xml2js")
const parserXml = new xml2js.Parser();
var val = [];
parserXml.parseString(data, (err, result) => {
STATUS = xpath.find(result, '//STATUS');
ERRORS = xpath.find(result, '//ERROR_CODE');
val.push(STATUS);
val.push(ERRORS);
}
Expected Result:
[ [ 'DONE', 'DONE' ], [ '', 'NO MESSAGE FOUND' ] ]
But I am getting this instead
[ [ 'DONE', 'DONE' ], [ 'NO MESSAGE FOUND' ] ]
How can I fix this to include blank value if the element doesn't exist in the XML node. Should I used a different library? What is the best way to handle this?
With XPath 3.1 (e.g. SaxonJS) you could use the XPath
array {
array { /message/return/string(STATUS) },
array { /message/return/string(ERROR_CODE) }
}
e.g.
const SaxonJS = require("saxon-js");
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<message>
<return>
<BYTES_LENGTH>12019</BYTES_LENGTH>
<STATUS>DONE</STATUS>
</return>
<return>
<BYTES_LENGTH>1129</BYTES_LENGTH>
<STATUS>DONE</STATUS>
<ERROR_CODE>NO MESSAGE FOUND</ERROR_CODE>
</return>
</message>`;
const result = SaxonJS.XPath.evaluate(`parse-xml(.) ! array {
array { /message/return/string(STATUS) },
array { /message/return/string(ERROR_CODE) }
}`, xml);
console.log(result);