Javascript 使用 xml2js 解析 xml 的节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10904448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:30:43  来源:igfitidea点击:

Node to parse xml using xml2js

javascriptxmlnode.jsxml-parsing

提问by sc_ray

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

我正在尝试使用 xml2js 解析和查询 xml 中的元素。我的xml字符串如下:

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

我想要的是提取其中的值并将其分配给 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?

这不起作用。有人可以指出我如何能够从我的 xml 中获取值吗?

Thanks

谢谢

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

这似乎不起作用。有人可以告诉我这里可能有什么问题吗?

回答by Andrey Sidorov

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