Skip to main content
Windward

What’s new in XPath 2.0?

What’s new in XPath 2.0?

In XPath 2.0 all XPath 1.0 queries are still valid, and should return the same results. XPath 2.0 adds some very powerful features to the language.

The “for” expression:

XPath 2.0 adds many key word based operations. The “for” expression is among the most powerful of these. One way it can be used is to do calculations with your data before it is returned. For example, consider the following expressions.

for $x in /order/item return $x/price * $x/quantity
sum(for $x in /order/item return $x/price * $x/quantity)

Quantifiers:

The “some” and “every” keywords can be used to see if there is an element in the set that satisfies a condition, or if every element in a set satisfies a condition. The expressions below will return true or false based on whether or not there is a student named Fred in the first case. The second example will only return true if every student is named Fred.

some $x in /students/student/name satisfies $x = "Fred"
every $x in /students/student/name satisfies $x = "Fred"

 

This is more powerful than the XPath 1.0 “=” expression because  $x = "Fred" can be replaced with comparisons other than equality.

 

Set operations:

XPath 2.0 has added functionality making it much easier using the keywords intersect, except, and union. For the below explanations E1 and E2 can be any arbitrary XPath expression.
The following expression uses the intersect keyword to select all nodes that are in both E1 and E2.

E1 intersect E2

 

Similar syntax can be used with the except keyword to sect all nodes that are in E1 unless they are also in E2.

E1 except E2

 

While the union keyword is new to XPath 2.0 union operations are not. In XPath 1.0 the | operator could be used to take a union of two sets. The union keyword may now be used in place of | in XPath 2.0, but the | operator is still valid. For example, the two expressions below both return all section nodes in a chapter or appendix of the selected book node.

/book/(chapter | appendix)/sections
/book/(chapter union appendix)/sections

 

Additional resources:

http://www.xml.com/pub/a/2002/03/20/xpath2.html - basic information on differences between XPath 1.0 and XPath 2.0
http://saxon.sourceforge.net/saxon7....pressions.html - detailed information on XPath 2.0 expression syntax
http://saxon.sourceforge.net/saxon7.9/functions.html - detailed information on XSLT 2.0 and XPath 2.0 functions
https://www.w3.org/TR/xpath20/ - XPath 2.0 official specification
 

  • Was this article helpful?