Skip to content

XPath Absolute and Relative Paths

How to use XPath absolute paths (starting with /) for precise node selection from the root and relative paths for context-based navigation within XML documents.

In XPath, a path expression is a query that navigates through the nodes of an XML document to select a specific node or a set of nodes. Just like you use a path to find a file in a file system, you use an XPath expression to find data in an XML document.

In XPath, there are two types of paths used specify the location of a node in XML documents: absolute paths and relative paths.

Absolute Path

An absolute path in XPath is like a full file path in an operating system (e.g., C:\Users\Documents). It always starts from the very top of the document (the root node) and provides a complete, unambiguous path to the target elements

An absolute path always begins with a single forward slash (/).

For example:

  • /bookstore/book: It will select book nodes within class root node.
<p><xsl:for-each select="/bookstore/book"></p>
  • /bookstore/book/author: It will select author of book node within class root node.
<p><xsl:value-of select="/bookstore/book/author"/></p>

Relative Path

A relative path does not start with a /. It selects nodes relative to the current context node. This is like navigating in a file system with commands like cd subfolder.

If location path starts with the node that we've selected then it is a relative path.

For example:

  • title: It selects title related to book nodes.
<p><xsl:value-of select="title"/></p>

Selecting Several Paths

Using the | operator in an XPath expression you can select several paths.

In the table below we have listed some example of path expressions and the result of the expressions:

Path Expression Result
//book/title | //book/price Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the document
/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price elements in the document
Navigation