74

Are there any cross-browser / cross-platform ways to parse XML files in Javascript?

3

3 Answers 3

73

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

Live demo:

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;

Sign up to request clarification or add additional context in comments.

8 Comments

This works, except in IE9 in standards mode. In IE9 standards mode to correct the issue, you just need to reform your initial if statement to be something like: if (window.DOMParser && typeof XMLDocument !== "undefined")
@GotDibbs: Really? The above example works fine for me in IE 9 standards.
Yep. Not sure if there's some other setting getting in the way here, but the moment I go into the dev toolbar and switch the browser mode to IE9 and document mode to IE9 standards it bombs without that additional check.
@GotDibbs: I know it's been a while, but here's a jsFiddle that works fine for me in IE 9 standards mode: jsfiddle.net/3s7Ly/1
@TimDown: If it is a working version, would you mind editing that into your answer?
|
7

Consider using jQuery.parseXML.

Note that old JQuery's code (pre 2.x) is essentially identical to one proposed in the accepted answer and can be found at http://code.jquery.com/jquery-1.9.1.js, partial version below:

// Cross-browser xml parsing
parseXML: function( data ) {
    ...
    try {
        if ( window.DOMParser ) { // Standard
            tmp = new DOMParser();
            xml = tmp.parseFromString( data , "text/xml" );
        } else { // IE
            xml = new ActiveXObject( "Microsoft.XMLDOM" );
            xml.async = "false";
            xml.loadXML( data );
        }
    } catch( e ) {
        xml = undefined;
    }
    ...
}

Starting JQuery 2.x code changed to skip ActiveX branch, if you still need it - use older version of JQuery or inline ActiveX parsing. Partial code from http://code.jquery.com/jquery-2.0.0.js:

// Cross-browser xml parsing
parseXML: function( data ) {
    var xml, tmp;
    .....
    // Support: IE9
    try {
        tmp = new DOMParser();
        xml = tmp.parseFromString( data , "text/xml" );
    } catch ( e ) {
        xml = undefined;
    }
    .....
},

3 Comments

jQuery.parseXml can be pretty slow. I would suggest looking at the post from @TimDown
Maybe it was a year ago, but looking at the source code of jQuery (code.jquery.com/jquery-1.9.1.js), I fail to see the difference from the TimDown's answer (omitting some error-handling logic).
@Zotov I've inlined your comment (post was rightfully downvoted as link-only, and your comment looked worth inlining rather than deleting the post).
4

If you need to parse large XML documents that you may not be able to completely hold in memory, consider using a SAX style parser like this one: https://github.com/isaacs/sax-js/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.