XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.


jQuery and XML

jQuery and XML

October 15, 2007

Whether you're an admirer of AJAX, or one who can't stand all the hype, if you're a web developer you must admit that it's proven very useful in driving explosive competition among JavaScript utility libraries. And the embarrassment of riches keeps on growing. jQuery emerged a couple of years ago to great acclaim for its performance, elegant design, and handy features, and now it's one of the most popular JavaScript frameworks.

jQuery offers a lot of facilities, but it's best known for offering a cross-browser model for accessing and manipulating web page elements that means you don't have to deal with the endless pain of DOM. jQuery can be used for XML processing on the Web as well as HTML processing, and in this article I show some examples of this use. In developing code examples for this article I downloaded the uncompressed bundle of jQuery 1.2.1 and tested on Firefox

The "X" in AJAX

The most cross-platform way to process XML these days is by using XMLHttpRequest. We can hope overall browser support of XML improves, but I'll start by showing how you can use jQuery to load and manipulate XML from an HTML web page. Listing 1 is a page representing a roster created from mailing labels in XML. When loaded all the user sees is a link. When the user clicks the link, the XML file is loaded and parsed to generate a list of names and IDs.

Listing 1. HTML with JavaScript to load XML for dynamic update
<!DOCTYPE html PUBLIC "-//W3C//  DTD HTML 4.01//EN"
     <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
     <title>Address book</title>
     <script src="jquery.js" type="text/javascript"></script>
     <script type="application/javascript">
     $(function() {
         $('#update-target a').click(function() {
                 type: "GET",
                 url: "labels.xml",
                 dataType: "xml",
                 success: function(xml) {
                         var id_text = $(this).attr('id')
                         var name_text = $(this).find('name').text()

                             .html(name_text + ' (' + id_text + ')')
                             .appendTo('#update-target ol');
                     }); //close each(
             }); //close $.ajax(
         }); //close click(
     }); //close $(
       <div id='update-target'>
         <a href="#">Click here to load addresses</a>

Notice the two script elements. The first loads the jQuery library itself, and the second is the page-specific script. I'll briefly explain the outlines of the code, but to understand the example better you'll want to check out the jQuery tutorials. The $(function() {}) construct is a special jQuery construct; the code block within the curly braces will not be executed until the document is fully loaded. This alone eliminates error-prone code every web developer has reinvented to prevent premature access of the DOM. The contained construct is also emblematic of jQuery—$('#update-target a') is a jQuery selector, much like a CSS selector, specifying anchor children of the element with ID update-target. jQuery selectors return a collection of all matching elements, and the code takes the first (and in this case only) selected element and sets an onClick event handler. The event handler is given as a parameter to the click method, in this case an AJAX invocation to load the XML document using the special jQuery $.ajax({}) construct.

jQuery of course gets a lot of headlines for making AJAX easier to work with, but that's not the point of this article. I kept the AJAX code bog-simple, and left out even error handling, so you can focus on what happens when the document is successfully loaded. This is the success item of the AJAX parameter structure, and it's another anonymous function. The resulting document is XML, and the function uses jQuery API to process that XML. The find method applies a jQuery selector to a context, rather than the whole document, and in this case it's applied relative to the loaded XML, selecting all the label elements. The each method specifies an action to be performed over all the selected elements, and this functional approach to iteration is another of jQuery's strengths, especially when dealing with DOM structures. For each label the id attribute's value is kept in a variable, using the attr method, and the text content of the name element is kept in another variable. The $('<li/>') constructs an element on the fly and the html method adds HTML, or in this case plain text, as the element content. Finally, this newly created element is added to the target ol element.

Listing 2 is the XML file that's loaded and parsed by the above code.

Listing 2: Address label XML
<?xml version="1.0" encoding="iso-8859-1"?>
   <label id='ep' added="2003-06-10">
     <name>Ezra Pound</name>
       <street>45 Usura Place</street>
   <label id='tse' added="2003-06-20">
     <name>Thomas Eliot</name>
       <street>3 Prufrock Lane</street>
   <label id="lh" added="2004-11-01">
     <name>Langston Hughes</name>
       <street>10 Bridge Tunnel</street>
   <label id="co" added="2004-11-15">
     <name>Christopher Okigbo</name>
       <street>7 Heaven's Gate</street>

Straight up XML

You can escape the safety of XML loaded through AJAX and still get a lot of use from jQuery, but it is certainly less steady ground because browsers are all over the place when dealing with XML directly. Listing 3 (designers.xml) is an example XML file you can load directly into a browser to generate a simple list display. The XML uses CSS to offer a reasonable look, and loads scripts to enable user interaction, in this case to simulate links.

Listing 3 (designers.xml): XML for browser viewing
<?xml version='1.0' encoding='utf-8'?>
 <?xml-stylesheet type="text/css" href="designers.css"?>
     <designer homepage="http://doria.co.uk">Doria Ltd.</ 
     of London
     <designer homepage="http://samsara.biz">Samsara Saris</ 
     of Mumbai
     <designer homepage="http://pcp.co.uk">Pikeman Camouflage,  
     of London
     <designer homepage="http://mandalay.co.jp">Mandalay</ 
     of Tokyo
   <xhtml:script xmlns:xhtml="http://www.w3.org/1999/xhtml"
   <xhtml:script xmlns:xhtml="http://www.w3.org/1999/xhtml"

The script elements are in the XHTML namespace, and are processed as such by most modern browsers. The first script element loads the jQuery library and the second the more specific script. Listing 4 is the referenced CSS file (designers.css).

Pages: 1, 2

Next Pagearrow