XPath programming consists of writing expressions to select the node/s you need to work with. Often, you're selecting the data within the nodes, but you could also be applying some programming logic in order to modify the output of your XML document.
To select a node (or set of nodes) in XPath, you use a location path. A location path is used to specify the exact path to the node you need to select. It's a bit like using the HTML <img src=""> tag to specify the location of an image - only, XPath is more powerful.
For example, here's a simple XPath expression to select the "title" node which is a child of the "rock" node, which in turn is a child of the "albums" node:
albums/rock/title
The above expression could be applied against the following XML document:
<albums> <rock> <title>Machine Head</title> <artist>Deep Purple</artist> </rock> <blues> <title>Greens From The Garden</title> <artist>Cory Harris</artist> </blues> <country> <title>The Ranch</title> <artist>The Ranch</artist> </country> </albums>
If we wanted to select the artist instead, we would use this location path:
albums/rock/artist
The above expression would select the artist node instead:
<albums> <rock> <title>Machine Head</title> <artist>Deep Purple</artist> </rock> <blues> <title>Greens From The Garden</title> <artist>Cory Harris</artist> </blues> <country> <title>The Ranch</title> <artist>The Ranch</artist> </country> </albums>
A location path consists of one or more location steps. The location steps are separated by either one forward slash (/) or two forward slashes (//) depending on the node you're trying to select.
Your location path can be absolute or relative. If your location path starts with the root node or a forward slash (/) you are using an absolute location path - your location path begins from the root node.
If your location path begins with the name of a descendant, you're using a relative location path. This node is referred to as the context node.
No comments:
Post a Comment