jQuery and XML namespaces: a solution

In my previous posts I did present a solution for selecting XML namespaces that was quite clunky. Thanks to Gianluca Troiani, I'm now aware of a simpler solution. This solution involves the use of a double backslash just before the ':' token of the XML suffix. Further, this is the standard procedure that jQuery uses to escape selectors inside an expression. So, given the following XML fragment:

<dvd xmlns:dvd="http://onwebdev.blogspot.com/ns/dvd">
 
 <dvd:item>
 
    <dvd:title>Mr. Jones</dvd:title>
    <dvd:year>1993</dvd:year>
 
 </dvd:item>
 
 <dvd:item>
 
    <dvd:title>Alien</dvd:title>
    <dvd:year>1977</dvd:year>
 
 </dvd:item>
 
 <dvd:item>
 
    <dvd:title>Dead Poets Society</dvd:title>
    <dvd:year>1989</dvd:year>
 
 </dvd:item>

</dvd>

we can write the following jQuery code:

$(document).ready(function() {


   $('dvd').find('dvd\\:item').each(function() {
   
   
       var $item = $(this);
       var $title = $item.find('dvd\\:title').text();
       var $year = $item.find('dvd\\:year').text();
       
       alert('DVD title: ' + $title + '\n' + 'DVD year :' + $year);
   
   });


});

That's a lot neater than using DOM properties (and more cross-browser).

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.