Skip to main content

XPath Absolute and Relative Paths

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 ExpressionResult
//book/title | //book/priceSelects all the title AND price elements of all book elements
//title | //priceSelects all the title AND price elements in the document
/bookstore/book/title | //priceSelects all the title elements of the book element of the bookstore element AND all the price elements in the document
note

You can learn more about Node Operators and Functions in our XPath Node Operators and Functions chapter.