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;
为了响应@gageeverante 对带有命名空间前缀的 xml 的关注。
Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:
注意: 这只适用于支持 xml 命名空间前缀(如 MicrosoftEdge)的浏览器
// 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);