Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda