Parsing XML with jQuery

There are currently two feasible approaches to XML parsing with JavaScript and Ajax: a DOM approach, which makes use of common XML DOM methods (such as getElementsByTagNameNS()) or just simple DOM methods, and a library-based one, which uses an underlying framework in order to perform some common tasks.

With the first approach, you have to:

  1. create an instance of the XMLHttpRequest object
  2. set the target content type (usually text/xml)
  3. open the given resource
  4. create a reference to a DOMDocument object
  5. use DOM methods to retrieve data

A rough example, just to give you an idea:

function getXMLData(xmlDoc) {
  xmlDoc = xmlDoc || documentElement;
  var items = xmlDoc.getElementsByTagName('item');
  var len = items.length;
  for (var i=0; i<len; i++) {
    // do something with each item
  }
}

With the second approach, instead, all the details of the request are simply automated, so with jQuery you have only to write a few lines of code, like the following:

$.get('rss.xml', function(data) {
  var items = $(data).find('item');
  items.each(function() {
    // do something with each item
  });
});

This approach is actually much simpler than the former. Using jQuery we don't need to understand the nuts and bolts of the current process. What we need is simply parse the XML file and all its elements and contents. That's all. Just remember a few gotchas:

  • be careful with resource URIs; sometimes a relative URI may trigger some errors during parsing, simply because browsers don't have the necessary server permissions to access the given resource (if so, use an absolute URI)
  • cache data in local variables for a better performance; remember that local is faster than global.

Leave a Reply

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