How to get value from XML string using Node.js

Let's say you have this xml:

<yyy:response xmlns:xxx='http://domain.com'> 
    <yyy:success> 
        <yyy:data>some-value</yyy:data> 
    </yyy:success> 
</yyy:response>

How do I get the value between <yyy:data>using Node.js?

Thank.

+6
source share
5 answers

node-xml2js will help you.

var xml2js = require('xml2js');

var parser = new xml2js.Parser();
var xml = '\
<yyy:response xmlns:xxx="http://domain.com">\
    <yyy:success>\
        <yyy:data>some-value</yyy:data>\
    </yyy:success>\
</yyy:response>';
parser.parseString(xml, function (err, result) {
    console.dir(result['yyy:success']['yyy:data']);
});
+11
source

You can make it easier with Camaro

const camaro = require('camaro')

const xml = '<yyy:response xmlns:xxx='http://example.com'> <yyy:success><yyy:data>some-value</yyy:data> </yyy:success></yyy:response>'

const template = {
    data: '//yyy:data'
}

console.log(camaro(xml, template))

Output:

{ data: 'some-value' }
+5
source

, regexp:

  str = "<yyy:response xmlns:xxx='http://example.com'> <yyy:success><yyy:data>some-value</yyy:data> </yyy:success></yyy:response>";
  var re = new RegExp("<yyy:data>(.*?)</yyy:data?>", "gmi");

  while(res = re.exec(str)){ console.log(res[1])}

 // some-value
+1

There are many methods for extracting information from an xml file. I used the xpath select method to extract tag values. https://cloudtechnzly.blogspot.in/2017/07/how-to-extract-information-from-xml.html

-1
source

All Articles