Reputation: 3189
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.
Upvotes: 9
Views: 30216
Reputation: 577
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.
Upvotes: 0
Reputation: 196
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' }
Upvotes: 6
Reputation: 4678
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
Upvotes: 3
Reputation: 1
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
Upvotes: -4
Reputation: 26219
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']);
});
Upvotes: 13
Reputation: 2922
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
Upvotes: 1