jQuery: selecting XML namespaces

jQuery was originally built with a syntax which quite resembled the XPath's formal grammar. This was due to the fact that jQuery can actually support both HTML and XML. But what happens when an XML document contains namespaces? Here's an example:

<book xmlns:xdc="http://www.xml.com/books">
  <xdc:bookreview>
   <xdc:title>XML: A Primer</xdc:title>
     <xdc:author>Simon St. Laurent</xdc:author>
     <xdc:price>31.98</xdc:price>
     <xdc:pages>352</xdc:pages>
     <xdc:date>1998/01</xdc:date>
  </xdc:bookreview>
</book>

In this case we have six elements which live inside the main namespace of the book element. Further, all these element have an XML suffix so that it's impossible to select them using normal jQuery's selectors. A good solution to this problem is using the namespaceURI and localName DOM properties to parse the above fragment. Here's how:

$(document).ready(function(){

   var NS = 'http://www.xml.com/books';
   var contents = [];
   
   $('book').find('*').each(function() {
   
       if($(this).get(0).namespaceURI == NS) {
       
           var local = $(this).get(0).localName;
           var content = $(this).text();
           
           var domBit = local + ': ' + content;
           
           contents.push(domBit);
       
       }
   
   });
   
   $('<ul></ul>').appendTo('body');
   
   for(var i= 0; len = contents.length, i<len; i++) {
   
   
       var part = contents[i];
       $('<li></li>').text(part).appendTo('ul');
   
   
   }
    
});

As you can see, we test the namespace stored in the NS variable against the namespace contained in each element. Further, the localName property is used to access the local name of each element, that is, the string that comes after the ':' token in an XML full qualified name. Notice that I had to use the CSS universal selector to access the children elements of book because any other approach would return null or rise a JavaScript error.

Unfortunately, IE6 and 7 don't support the aforementioned DOM properties. However, if we insist on supporting obsolete browsers, we'll probably miss one important thing: the web is evolving and there's no time for dinosaurs.

Leave a Reply

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