9.1. Location Paths
For all its power and flexibility, the location path is probably the easiest type of XPath to start with. Using the XML document in Listing 9-1 as a starting point, let's say that we want to get the root node. This can be accomplished by using the following XPath:
That's all there is to it. Remembering that there is a difference between the root node and the root element, the root element can be obtained by either of the two following XPath statements:
The first example implicitly specifies the root element by name. The second example uses a wildcard (*). Wildcards can be used to increase the flexibility of the XPath by making it unnecessary to know the individual node names. All that is required is the knowledge that we want the root element.
Before going any further, I'd like to introduce one of those pesky new concepts called a node set. A node set is a collection of nodes returned by an XPath statement; think SQL and SELECT with multiple rows returned, and you get the idea. With this in mind, let's say that we want the book elements from the XML document in Listing 9-1. This can be accomplished by any of the following XPath statements:
/library/book /*/book /library/* /*/* //book
The first four examples shown here are all a logical progression of the basic location path covered previously. The last example, however, is something else entirely. The double forward slash (//) refers to descendants of the root node, as well as to the root node itself. For example, //* refers to the root element and every element node in the document.