How do location paths work? As we're going to see in Chapter 3, location paths are much like the standard file directory paths that you're already familiar with. For example, you might store data on stocks for April 2004 in a directory with this path if you're using Windows:
or this path if you're using Unix:
That's much how a location path works. A location path consists of one or more location steps , separated by / or // . You use successive stepsseparated by / to get to the data you want, just as you use successive directories in a file path to narrow down the location of a file. Starting the whole location path with a / means that you're starting from the root node (the very beginning of the document, before anything else), and working from that point.
As we're going to see in Chapter 3, a location step, in turn , is made up of an axis , a node test , and zero or more predicates .
Here's an example. In the location step child::planet[position() = 5] , child is the name of the axis (which you follow with :: ), planet is the node test, and [position() = 5] is a predicate. In this case, the child axis selects child nodes of the node you start from. The node test, planet , will match <planet> elements. And the predicate consists of an XPath function, position , that must return a value of 5 to make the predicate true. Putting all that together, then, this location step selects the fifth <planet> child element.
You create location paths with one or more location steps, such as /child::planet[position() = 5]/child::name , which starts at the root node and selects all the <name> elements that are children of the fifth <planet> child element in the document.
The evaluation of each location step in a location path starts at its context node . The idea of a context node is an important one, because as you navigate deep into an XML document, each successive location step starts from a different location, which XPath calls the location step's context node. In the present example, / makes the context node the document's root node for the next location step, which is child::planet[position() = 5] . That location step in turn makes the context node the fifth <planet> child element for the next location step, which is child::name . The thing to remember is that the evaluation of each location step starts from its context node.
Here are a number of location path examples to get us startedwe're going to see how to create these in detail over the next three chapters, so don't try to memorize any of these now. But it's worth taking a look at these examples in overview:
As you can see, some of this syntax is pretty involved, and a little lengthy to type. However, there is an abbreviated form of XPath syntax, as we're going to see in Chapter 3.