XPath Absolute Path
XPath is a query language used to select elements or attributes of an XML document. An absolute path in XPath starts with the root node and includes the complete path to the selected node. In this tutorial, we will learn about absolute path in XPath.
Syntax
The syntax for an absolute path in XPath is:
/RootNode/ChildNode[@attribute='value']/GrandChildNode
In the above syntax, /
represents the root node, RootNode
is the name of the root node, ChildNode
is the name of the child node, @attribute='value'
is an optional attribute selector, and GrandChildNode
is the name of the grandchild node.
Example
Consider the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
</catalog>
Absolute Path Example 1
To select the author
element of the first book
element, the XPath absolute path would be:
/catalog/book[1]/author
Absolute Path Example 2
To select the price
attribute of the second book
element, the XPath absolute path would be:
/catalog/book[2]/@price
Output
The output of the XPath absolute path in the above examples would be:
Gambardella, Matthew
and
5.95
Explanation
In Example 1, the absolute path /catalog/book[1]/author
selects the first book
element using the [1]
index selector, and then selects the author
element.
In Example 2, the absolute path /catalog/book[2]/@price
selects the second book
element using the [2]
index selector, and then selects its price
attribute using the @
attribute selector.
Use
Absolute paths are useful when you need to select elements or attributes that are located at a fixed position within the XML document. They are also useful when the XML document has a simple structure, and relative paths are not required.
Important Points
- Absolute paths start with the root node
/
. - The path includes the complete path to the selected node.
- Attribute selectors use the
@
symbol before the attribute name.
Summary
In this tutorial, we learned about absolute path in XPath. We saw examples and output for selecting elements and attributes using an XPath absolute path. We also learned about the use and important points to keep in mind while using an absolute path.