Site icon Tutorial

Absolute Location paths and descendant selection

Location Paths

Although there are many different kinds of XPath expressions, the one that’s of primary use in Java programs is the location path. A location path selects a set of nodes from an XML document. Each location path is composed of one or more location steps. Each location step has an axis, a node test and, optionally, one or more predicates. Furthermore, each location step is evaluated with respect to a particular context node. A double colon (::) separates the axis from the node test, and each predicate is enclosed in square brackets.

Example Location Path

Consider the following XML document:

Code

<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 “title” node of all albums, we could use the following (absolute) location paths:

Code

albums/rock/title
albums/blues/title
albums/country/title

The Result

Here are the nodes that are selected using the above location path.

Code

<title>Machine Head</title>
<title>Greens From The Garden</title>
<title>The Ranch</title>

The Root Node

If we wanted to select the root node, we could use either the node’s name or a forward slash. Both of these options are absolute location paths and select the root node.

Option 1 – use the root node’s name:

Code

albums

Option 2 – use a forward slash:

Code

Exit mobile version