AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 163


PART I


var items = xmlDoc.selectNodes("//bookmark");
for (var i=0;i<items.length;i++)
{
var title = items[i].selectNodes("title/text()")[0].text;
var url = items[i].selectNodes("url/text()")[0].text;
...snip...
/* print out the complete bookmark */
}

Again, we omit the gory output details and direct interested readers to view the complete
Internet Explorer–specific version at http://ajaxref.com/ch4/xmlxpathie.html.
Given that you have seen both of the major browsers support XPath, it is certainly
possible, as done previously, to create a wrapper to abstract the differing details away. In the
case of XPath and XSLT (to be discussed shortly), this is more than a bit of a chore, so we
opt to use one of the popular libraries online to do the task, in this case Sarissa (http://
sourceforge.net/projects/sarissa). Once the Sarissa library is included, we fetch the XML
tree, but then inform Sarissa that we will be using XSLT and XPath:

xmlDoc = xhr.responseXML;
xmlDoc.setProperty('SelectionNamespaces',
'xmlns:xsl="http://www.w3.org/1999/XSL/Transform"');
xmlDoc.setProperty('SelectionLanguage', 'XPath');

Now we run a selection to fetch the list of <bookmark> tags and once again iterate over
the list pulling out the values within each tag. You’ll note that the syntax Sarissa provides is
similar to the IE style, which is a bit cleaner than the Firefox approach.

var items = xmlDoc.selectNodes("//bookmark");
for (var i=0;i<items.length;i++)
{
var title = items[i].selectSingleNode("title").firstChild.nodeValue;
var url = items[i].selectSingleNode("url").firstChild.nodeValue;
... snip ...
/* print out the complete bookmark */
}

The Sarissa example, which works in a multitude of browsers, can be found at
http://ajaxref.com/ch4/xmlxpathsarissa.html. A version that uses the Google AJAXSLT
library (http://goog-ajaxslt.sourceforge.net/) is also supplied online at http://ajaxref.com/
ch4/xmlxpathgoogle.html, in case readers prefer this library.

Transforming Responses with XSLT

XSLT (eXtensible Style Language Transformations) is a powerful technology used to
convert one markup language to another (www.w3.org/TR/xslt). A common use of XSLT
is to create XHTML output templates from XML documents. We could spend a tremendous
amount of time explaining the syntax of XSLT, but instead we focus here on its application
within our simple example to illustrate the approach and pique reader’s interest in the
technology.
Free download pdf