如何使用Node.js从XMLstring中获取值

假设你有这个xml:

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

我将如何检索使用Node.js <yyy:data>之间的值?

谢谢。

node-xml2js库将帮助你。

 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']); }); 

您可以使用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) 

输出:

 { data: 'some-value' } 

首先,您需要一个库来parsingXML。 核心节点不提供XMLparsing。

你可以在这里find它们的列表: https : //github.com/joyent/node/wiki/modules#wiki-parsers-xml

我会build议使用libxmljs

你不必parsing它的数据提取,只需使用正则expression式:

  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 

有很多方法可以从xml文件中提取信息,我使用xpath select方法来获取标签值。 https://cloudtechnzly.blogspot.in/2017/07/how-to-extract-information-from-xml.html