Chapter 4: Data Formats 161
PART I
walking that relies on the known structure of the packet. As an alternative to this scheme,
XPath could be employed. The next few simple examples should give you the idea of what
is involved with this technology. For example, if you want to create an XPath expression to
fetch each individual <bookmark> element use the expression:
//bookmark
Or, you could alternatively use a hard path, like:
/bookmarklist/bookmark
but the former is more flexible. If you were interested in fetching all the individual URLs
inside of bookmark elements, you could use an expression like:
//bookmark/url
If you wanted to fetch the description of the second bookmark you would use:
//bookmark[2]/description
You can also select by using attributes if you like. To pull out titles of bookmarks with
the attribute class you would use:
//bookmark[@class]/description
Or you could restrict the query to focus only on attributes set to a particular value:
//bookmark[@class="favorite"]/description
Xpath supports a number of interesting functions such as first() and last(), which
can find useful positions in a node list. For example:
//boomark[first()]/url
//bookmark[last()]/url
would return the URLs of the first and last items in the document. You can combine expressions
using the | character. The following does the same as the previous two examples:
//boomark[first()]/url | //bookmark[last()]/url
This should give you a test of the XPath format and show that the path structure it uses
can make it quite simple to slice through even complex XML documents.
As a test of XPath, let’s fetch the bookmark list and populate it into an XHTML table for
display. The goal can be seen in Figure 4-7. Now, let’s jump right to the not-so-surprising
bad news: the browsers support XPath differently. In the case of Firefox, you can use
document.evaluate() and pass it an XPath expression to apply to a passed DOM tree.
For example, the following bit of code would take the responseXML contents and apply a
simple expression to pull out all the <bookmark> tags:
var xmlDoc = xhr.responseXML;
var items = document.evaluate('//bookmark', xmlDoc, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );