AJAX - The Complete Reference

(avery) #1

160 Part I: Core Ideas


}
return null;
}

var xmlDoc = xhr.responseXML;
var average = bruteGetElementById("average", xmlDoc).firstChild.nodeValue;

From a performance point of view, this solution is not going to be very nice if the tree is
quite large, but in the use of XML with Ajax this is not so likely. To see this solution in action
please visit the example at http://ajaxref.com/ch4/xmlgetelementbyidbrute.html.

Processing Responses with XPath

Rather than solving the problem of quick reference to XML-based content using DOM
methods, maybe an alternate technology like XPath (www.w3.org/TR/xpath) should be
used. XPath provides a relatively concise way to access portions of XML documents and
provides an alternative to the DOM access methods. Only the briefest discussion of XPath
syntax is presented here for readers to follow the example.

NNOT EOTE XPath 2 was made a W3C recommendation in early 2007 (www.w3.org/TR/xpath20/).
However, given that browsers have been slow to implement even XPath 1 properly, the focus has
remained on the older specification.

In the example, a much larger amount of XML in the form of a list of interesting sites
bookmarks will be returned. The bookmark list will contain individual bookmarks each
containing a title, URL, description, rating, the date and time of the last visit, and a count of
the total number of visits. A snippet of the format is shown next with the full file available
at http://ajaxref.com/ch4/bookmarks.xml.

<?xml version="1.0" encoding="UTF-8"?>
<bookmarklist>
<bookmark>
<title>Google</title>
<url>http://www.google.com</url>
<description>Billions of documents and billions of dollars!</description>
<rating>5</rating>
<lastvisit>March 8, 2007 8:59 PM</lastvisit>
<totalvisits>250</totalvisits>
</bookmark>
<bookmark class="favorite">
<title>Yahoo</title>
<url>http://www.yahoo.com</url>
<description>Thanks for the great Ajax library with docs even</description>
<rating>5</rating>
<lastvisit>March 1, 2007 3:05 PM</lastvisit>
<totalvisits>47</totalvisits>
</bookmark>
</bookmarklist>

If you build an Ajax application to fetch this file and then paint it on the screen using
DOM methods, you would see heavy use of getElementsByTagName() or some tree
Free download pdf