9

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 would I retrieve the value in between <yyy:data> using Node.js?

Thanks.

6 Answers 6

13

node-xml2js library 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']);
});
Sign up to request clarification or add additional context in comments.

Comments

6

You can do 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' }

Comments

3

You don't have to parse it for data extraction, simply use 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

Comments

1

First, you'll need a library to parse the XML. Core Node does not provide XML parsing.

You'll find a list of them here: https://github.com/joyent/node/wiki/modules#wiki-parsers-xml

I would recommend using libxmljs

Comments

0

Use XMLDOM library A JavaScript implementation of W3C DOM for Node.js, Rhino and the browser. Fully compatible with W3C DOM level2; and some compatible with level3. Supports DOMParser and XMLSerializer interface such as in browser.

Comments

-4

There are plenty of methods available to extract information from xml file, I have used xpath select method to fetch the tag values. https://cloudtechnzly.blogspot.in/2017/07/how-to-extract-information-from-xml.html

2 Comments

Linking a solution is not a good answer. Please summarise the essence of the solution here or give a code sample.
checkout this link ,then u may get some ideas cloudtechnzly.blogspot.in/2017/08/xml-to-json-conversion.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.