Decoding jQuery – $.parseXML: Cross-browser XML parsing

In the Decoding jQuery series, we will break down every single method in jQuery, to study the beauty of the framework, as an appreciation to the collective/creative geniuses behind it.

jQuery.parseXML()
jQuery.parseXML uses the native parsing function of the browser to create a valid XML Document.

An example usage is:

var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find("title");
console.log($title.text( "XML Title" ));
// return "XML Title"

Let’s take a look at the source to see how it actually works:

parseXML: function(data, xml, tmp) {
 
    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);
    }
 
    tmp = xml.documentElement;
 
    if (!tmp || !tmp.nodeName || tmp.nodeName === "parsererror") {
        jQuery.error("Invalid XML: " + data);
    }
 
    return xml;
}

DOMParser is available to web pages, but it’s not part of any standard and is not supported by some browsers, guess what that some browser is? Yea, IE… Unfortunately, Internet Explorer does not support it. So if window.DOMParser returns false, we will use ActiveXObject("Microsoft.XMLDOM") instead. (Edit: from IE9 onwards, window.DOMParser is recognized)

Note, this method is used to parse strings and streams of XML text, if you want to parse XML received from the server, you can just use the responseXML property of XMLHttpRequest for which we will introduce in a different jQuery method.

Reference:
jQuery source on github: https://github.com/jquery/jquery/blob/master/src/core.js#L555
DOMParser under MDN Docs: https://developer.mozilla.org/en/DOMParser
Van Steenbeek’s article: https://sites.google.com/a/van-steenbeek.net/archive/explorer_domparser_parsefromstring

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

About Shi Chuan

I am a web developer.
This entry was posted in JavaScript and tagged , . Bookmark the permalink.

3 Responses to Decoding jQuery – $.parseXML: Cross-browser XML parsing

  1. Chris says:

    DOMParser is available now in IE9!

  2. Pingback: Apprendre jQuery

  3. Keith says:

    FYI
    I think there is a typo one your example one
    “XML Title” should be “RRS Title”

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">