小编典典

跨浏览器Javascript XML解析

javascript

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


阅读 521

收藏
2020-04-25

共1个答案

小编典典

以下内容适用于所有主要浏览器,包括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;
2020-04-25