Quantcast
Channel: Coding and Programing » javascript
Viewing all articles
Browse latest Browse all 10

Cross-Browser Javascript XML Parsing

$
0
0

Problem And Question

Whats the easiest cross-browser/cross-platform way to parse XML files in Javascript?

Best Solution And Answer

The following will work in all major browsers, including 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");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Viewing all articles
Browse latest Browse all 10

Trending Articles