XPath 2.0 tips
Learn about XPath 2.0 functions, examples, and issues.
XPath 2.0 support can vary by automation framework. In Appium-based tests, the iOS XCUITest and Android UIAutomator2 drivers can evaluate some locators with XPath 1.0 behavior, so some XPath 2.0 expressions may fail depending on driver behavior and context. For workaround patterns, see XPath 2.0 updates and workarounds.
On this page:
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 |
To learn more, see the XPath 2.0 function reference.
Examples
-
Use the
matches()function with regular expressions. For example://*[matches(@text,‘.*5ghz$')]
is the equivalent of:
//*[ends-with(@text,'5ghz')]
-
XPath 2.0 is more flexible with case. You no longer need to use the
translate()function for this.The 3rd parameter of the
matches()function ‘i’ means case insensitive. Newlower-case()andupper-case()functions are available. -
You can shorten the existing XPath:
//*[@resource-id=“com.perfectomobile.example.test.home:id/btnNewSalePage"]
to the following:
//*[matches(@resource-id,'.*newsalepage','i')]
Issues
XPath 1.0 compatibility warning
The contains() function behaves differently with XPath 2.0. This type of statement will cause an error:
//*[contains(text(),’ABC’)]
Change this type of XPath to one of the following:
//tagname[contains(text(),’ABC’)]
//*[text()[contains(.,'ABC')]]
//*[matches(@text,’.*.*’)]