XPath 2.0 tips

This article covers XPath 2.0 function reference, examples, and issues.

XPath 2.0 functions

Functions in Bold are only available in 2.0. The others are also supported by XPath 1.0.

Purpose

Example functions

General string handling

lower-case, upper-case, substring, substring-before, substring-after, translate, starts-with, ends-with, contains, string-length, concat, normalize-space, normalize-unicode

Regular expressions

matches, replace, tokenize

Arithmetic

count, sum, avg, min, max , round, floor, ceiling, abs

Dates and times

adjust-dateTime-to-timezone, current-dateTime, day-from-dateTime, month-from-dateTime, days-from-duration, months-from-duration, etc.

Properties of nodes

name, node-name, local-name, namespace-uri, base-uri, nilled

See also XPath 2.0 function reference.

Examples

  • Use matches() function with regular expressions

    //*[matches(@text,‘.*5ghz$')]

    is the equivalent of:

    //*[ends-with(@text,'5ghz')]
  • 2.0 is more flexible with case.

    You no longer need to use the translate() function for this.

    The 3rd parameter of matches() function ‘i’ means case insensitive.

    New lower-case() and upper-case() functions are available.

  • Use to shorten existing XPath

    //*[@resource-id=“com.perfectomobile.example.test.home:id/btnNewSalePage"]

    can become:

    //*[matches(@resource-id,'.*newsalepage','i')]

Issues

XPath 1.0 compatibility warning

The contains() function behaves differently with 2.0.

This type of statement will cause an error:

//*[contains(text(),’ABC’)]

Change this type of XPath one of the following ways:

  • //tagname[contains(text(),’ABC’)]
  • //*[text()[contains(.,'ABC')]]
  • //*[matches(@text,’.*.*’)]