Updated answer for 2017
(更新了2017年的答案)
The following will parse an XML string into an XML document in all major browsers.
(下面将在所有主要浏览器中将XML字符串解析为XML文档。)
Unless you need support for IE <= 8 or some obscure browser, you could use the following function:(除非需要支持IE <= 8或某些晦涩的浏览器,否则可以使用以下功能:)
function parseXml(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}
If you need to support IE <= 8, the following will do the job:
(如果您需要支持IE <= 8,则可以执行以下操作:)
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");
}
Once you have a Document
obtained via parseXml
, you can use the usual DOM traversal methods/properties such as childNodes
and getElementsByTagName()
to get the nodes you want.
(通过parseXml
获得Document
parseXml
,就可以使用常规的DOM遍历方法/属性,例如childNodes
和getElementsByTagName()
来获取所需的节点。)
Example usage:
(用法示例:)
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
If you're using jQuery, from version 1.5 you can use its built-in parseXML()
method, which is functionally identical to the function above.
(如果您使用的是jQuery,则从1.5版开始,您可以使用其内置的parseXML()
方法,该方法在功能上与上述功能相同。)
var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…