XPath Location Path - Relative
Now that we've looked at absolute location paths, let's look at relative location paths.
A relative location path is one where the path starts from the node of your choosing — it doesn't need to start from the root node. This can reduce the amount of code you need to write — especially if you need to select many nodes that share the same name.
Example of a Relative Location Path
Consider the following XML document:
If we wanted to select the
title node of all albums, we could use the following (relative) location path:
This single line of code has exactly the same result as the example in the previous lesson. The only difference is that, in the previous lesson, we needed 3 lines of code to provide the same result.
So to just to make sure you understand what this line of code is doing, it is selecting all title nodes within our XML document. We don't need to provide the full path — just the name of the node we need to work with. This makes our like easier and keeps our code nice and clean.
We can also select a node's children using relative location paths.
Example 1: Selecting the two children of the
rock node (
artist). The context node is
rock, because that's where our relative path starts:
Example 2: Using a wildcard to select all children of the
rock node. This (single line of code) has the same result as the above two lines of code. Further, if another node was added to the XML document under the
rock node, it would be automatically included using the wildcard:
About the Wildcard
If you don't know what I mean by "wildcard", it is represented by the asterisk (
*). The wildcard represents any node that would be located where the wildcard is positioned. Therefore, using our example, it is representing any node that comes under the
Wildcards don't have to appear at the end of a location path — they can also appear in the middle of a location path. We aren't limited to just one either — we could use as many as we like within a location path.