Node to parse xml using xml2js

微笑、不失礼 提交于 2019-12-04 18:23:48

问题


I am trying to parse and query for an element within an xml using xml2js. My xml string is as follows:

var xml = "<config><test>Hello</test><data>SomeData</data></config>";

What I want is to extract the value in and assign it to var extractedData

Here's what I have so far:

var parser = new xml2js.Parser();
parser.parseString(xml, function(err,result){
  //Extract the value from the data element
  extractedData = result['data'];
}

This does not work. Can somebody point out how I might be able to grab the values from my xml?

Thanks

This doesn't seem to be working. Can somebody tell me what might be the issue here?


回答1:


it works for me

var xml2js = require('xml2js');
var xml = "<config><test>Hello</test><data>SomeData</data></config>";

var extractedData = "";
var parser = new xml2js.Parser();
parser.parseString(xml, function(err,result){
  //Extract the value from the data element
  extractedData = result['config']['data'];
  console.log(extractedData);
});
console.log("Note that you can't use value here if parseString is async; extractedData=", extractedData);

result:

SomeData
Note that you can't use value here if parseString is async; extractedData= SomeData


来源:https://stackoverflow.com/questions/10904448/node-to-parse-xml-using-xml2js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!