跨浏览器Javascript XML解析

是否有任何跨浏览器/跨平台的方法来解析Javascript中的XML文件?

回答:

以下内容适用于所有主要浏览器,包括IE 6:

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");

}

用法示例:

var xml = parseXml("<foo>Stuff</foo>");

alert(xml.documentElement.nodeName);

现场演示:

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");

}

var xml = parseXml("<foo>Stuff</foo>");

document.body.innerHTML = "Root element: " + xml.documentElement.nodeName;

以上是 跨浏览器Javascript XML解析 的全部内容, 来源链接: utcz.com/qa/417478.html

回到顶部