Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
How to set default value for missing elements in XML using XPath?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!