Cover Image for XPath Relative Path
144 views

XPath Relative Path

In XPath, a relative path is a path expression that starts from the context node (the current node) and navigates to other nodes relative to that context node. Relative paths are used to specify the location of nodes in relation to the context node without specifying the entire document’s structure.

The context node can change depending on where the XPath expression is used. For example, if you are at a specific element in the XML or HTML document, the context node will be that element, and the relative path will be resolved from there.

Here are some examples of relative XPath paths:

Consider the following XML document:

<bookstore>
  <book>
    <title>Harry Potter</title>
    <author>J.K. Rowling</author>
  </book>
  <book>
    <title>The Hobbit</title>
    <author>J.R.R. Tolkien</author>
  </book>
</bookstore>
  1. Relative Path to Select the <title> Elements:
bookstore/book/title

This relative path selects all <title> elements within the <book> elements under the <bookstore> element.

  1. Relative Path to Select the <author> Element of the First <book>:
bookstore/book[1]/author

This relative path selects the <author> element within the first <book> element under the <bookstore> element.

  1. Relative Path to Select the <title> Element with Specific Text:
bookstore/book/title[text()='Harry Potter']

This relative path selects the <title> element with the exact text “Harry Potter” under the <book> elements within the <bookstore> element.

  1. Relative Path to Select the <title> Element with Attribute Value:
bookstore/book[@category='fantasy']/title

This relative path selects the <title> element within the <book> elements that have a “category” attribute with the value “fantasy” under the <bookstore> element.

Relative paths are handy when you want to locate nodes based on their relationship to the context node, without specifying the entire document’s structure. They allow for more concise and context-aware XPath expressions, making it easier to work with XML or HTML data in various situations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS