xml
  1. xml-xpath-predicate

XML XPath Predicate

  • XPath Predicate is a powerful feature of XPath that allows for more precise querying of XML documents.
  • A predicate is used to filter out specific nodes in an XML document that match a certain condition.

Syntax

The syntax for XPath Predicate is as follows:

XPathExpression[Predicate]

Example

Consider the following XML document:

<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter and the Philosopher's Stone</title>
    <author>J.K. Rowling</author>
    <year>1997</year>
    <price>12.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

To find all books with a price greater than 20, the following XPath expression with a predicate can be used:

/bookstore/book[price > 20]

This will return the following output:

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

Explanation

In the example above, the predicate is [price > 20] which filters out only those book elements whose price element is greater than 20. This results in only two matching book elements being returned.

Use

XPath Predicate can be used to filter out specific nodes that match a certain condition in an XML document. It is particularly useful when you want to select nodes that meet a specific set of criteria.

Important Points

  • A predicate is always enclosed in square brackets [].
  • Predicates can be used to filter out nodes based on a wide range of conditions such as comparison, mathematical, and logical operations.
  • Multiple predicates can be applied to an XPath expression to refine the query result.

Summary

XPath Predicate is a powerful feature of XPath that allows for more precise querying of XML documents. It is used to filter out specific nodes that match a certain condition, and is particularly useful when you want to select nodes that meet a specific set of criteria. Predicates are always enclosed in square brackets [], and multiple predicates can be applied to an XPath expression to refine the query result.

Published on: