Queries That Return More Than You Want

Suppose you want the titles of all the books. You might decide to define your query like this:

//title
               

            

This query does return all titles of books, but it also returns the title of a magazine. This query instructs the XPath processor to start at the root node, search all descendants, and return all title elements. In bookstore.xml, this means that the query returns the title of the magazine in addition to the titles of books. In some other document, if all titles are contained in book elements, this query returns exactly what you want.

To query and obtain only the titles of books, you can use either of the following queries. They obtain identical results. However, the first query runs faster.

/bookstore/book/title
               
//book/title
               
 
               

            

The first query runs faster because it uses the child axis, while the second query uses the descendent-or-self axis. In general, the simpler axes, such as child, self, parent, and ancestor, are faster than the more complicated axes, such as descendent, preceding, following, preceding-sibling, and following-sibling. This is especially true for large documents. Whenever possible, use a simpler axis.

 
Free Stylus Studio XML Training: