使用 JavaScript 解析 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17604071/
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
Parse XML using JavaScript
提问by user2574350
I need to be able to parse XML using JavaScript. The XML will be in a variable. I would prefer not to use jQuery or other frameworks.
我需要能够使用 JavaScript 解析 XML。XML 将在一个变量中。我不想使用 jQuery 或其他框架。
I have looked at this, XML > jQuery reading.
我看过这个,XML > jQuery reading。
回答by Enigmadan
I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.
我从你的最后一个问题中猜测,在这个问题之前 20 分钟,你正在尝试解析(读取和转换)通过使用 GeoNames 的 FindNearestAddress 找到的 XML。
If your XML is in a string variable called txtand looks like this:
如果您的 XML 位于名为的字符串变量中txt,如下所示:
<address>
<street>Roble Ave</street>
<mtfcc>S1400</mtfcc>
<streetNumber>649</streetNumber>
<lat>37.45127</lat>
<lng>-122.18032</lng>
<distance>0.04</distance>
<postalcode>94025</postalcode>
<placename>Menlo Park</placename>
<adminCode2>081</adminCode2>
<adminName2>San Mateo</adminName2>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<countryCode>US</countryCode>
</address>
Then you can parse the XML with Javascript DOM like this:
然后你可以像这样用 Javascript DOM 解析 XML:
if (window.DOMParser)
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
And get specific values from the nodes like this:
并从节点获取特定值,如下所示:
//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;
//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;
//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
Feb. 2019 edit:
2019 年 2 月编辑:
In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:
为了回应@gaugeinvariante 对带有命名空间前缀的 xml 的担忧。如果您需要使用 Namespace 前缀解析 xml,一切都应该几乎相同:
NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge
注意:这仅适用于支持 xml 命名空间前缀的浏览器,例如 Microsoft Edge
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt
txt = `
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>
<s:street>Roble Ave</s:street>
<sn:streetNumber>649</sn:streetNumber>
<p:postalcode>94025</p:postalcode>
</address>`;
//Everything else the same
if (window.DOMParser)
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
//The prefix should not be included when you request the xml namespace
//Gets "streetNumber" (note there is no prefix of "sn"
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);
//Gets Street name
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);
//Gets Postal Code
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
回答by faino
The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.
下面将在所有主要浏览器(包括 Internet Explorer 6)中将 XML 字符串解析为 XML 文档。一旦有了它,您就可以使用常用的 DOM 遍历方法/属性(例如 childNodes 和 getElementsByTagName())来获取您想要的节点。
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
用法示例:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Which I got from https://stackoverflow.com/a/8412989/1232175.

