jQuery: the parseXML() method

Web developers are all accustomed to use the XML format as one of their preferred formats when retrieving the results of an AJAX request. Although in the last years the JSON format has gained its momentum in AJAX, the XML format remains a valid option when you need to get structured and complex data. But how jQuery parses XML? Simply put, it uses its private method called parseXML().

This method has the following implementation:

// Cross-browser xml parsing
// (xml & tmp used internally)
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;
}

As with many jQuery's methods, the W3C DOM procedure is tried first, in this case using the DOMParser feature. Since some versions of Internet Explorer don't support this procedure, an alternate method is tried by using an ActiveX object. If everything goes fine and the XML document passed to this method as a string is a valid XML document (that is, it's well-formed), then the XML document itself is returned. Otherwise, jQuery triggers and error and sends it to the JavaScript console.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.