Descending Along Branches

Sometimes you want the XPath processor to evaluate all nodes that are descendants of a node and not just the immediate children of that node. This amounts to operating on a branch of the tree that forms the document.

To specify the evaluation of descendants that starts at the root node, insert two forward slashes ( //) at the beginning of a query.

To specify the evaluation of descendants that starts at the context node, insert a dot and two forward slashes ( .//) at the beginning of the query.

Following is a query that finds all last-name elements anywhere in the current document:

 //last-name
               

            

Suppose the context node is the first book element in the document. The following query returns a single last-name element because it starts its search in the current context:

.//last-name
               

            

At the beginning of a query, / or // instructs the XPath processor to begin to evaluate nodes at the root node. However, between tag names, / is a separator, and // is an abbreviation for the descendant-or-self axis.

The // selects from all descendants of the context node set. For example:

book//award
               

            

This query searches the current context for book child elements that contain award elements. If the bookstore element is the context node, this query returns the two award elements that are in the document.

For the sample bookstore data, the following two queries are equivalent. Both return all last-name elements in the document.

//last-name
               
//author//last-name
               

            

The first query returns all last-name elements in the sample document or in any XML document. The second query returns all last-name elements that are descendants of author elements. In the sample data, last-name elements are always descendants of author elements, so this query returns all last-name elements in the document. But in another XML document, there might be last-name elements that are not descendants of author elements. In that case, the query would not return those last-name elements.

Tip: // is useful when the exact structure is unknown. If you know the structure of your document, avoid the use of //. A query that contains // is slower than a query with an explicit path.

 
Free Stylus Studio XML Training: