Cheatsheet: XPath

Last updated 2026-06-21

Paths and node tests

Select the document root.

/

Select car elements that are direct children of the cars root element.

/cars/car

Select car elements anywhere in the document.

//car

Select the current context node.

.

Select the parent of the current context node.

..

Use a wildcard to select any child element under cars.

/cars/*

Use union to combine results from multiple paths.

//car | //truck

Attributes and predicates

Select elements by attribute value.

/cars/car[@make="lexus"]

Select the make attributes from all car elements.

//car/@make

Select elements that have a specific attribute regardless of value.

//car[@vin]

Select the first car child for each cars element.

/cars/car[1]

Select the last car child for each cars element.

/cars/car[last()]

Select cars with price greater than 30000.

//car[price > 30000]

Combine predicate conditions with and.

//car[@make="lexus" and year >= 2022]

Axes

Select all descendant model elements below each car.

//car/descendant::model

Select ancestor cars elements for matching model nodes.

//model[text()="RX"]/ancestor::car

Select the parent element of each model node.

//model/parent::*

Select following sibling elements after a title.

//title/following-sibling::*

Select preceding sibling elements before a price.

//price/preceding-sibling::*

Select all attributes with the attribute axis.

//car/attribute::*

Functions

Match exact text content of an element.

//name[text()="Roadster"]

Select elements whose text contains a substring.

//name[contains(text(), "Road")]

Select elements whose attribute starts with a prefix.

//car[starts-with(@id, "car-")]

Normalize whitespace before comparing text.

//button[normalize-space()="Save"]

Select by numeric position using position().

//car[position() <= 3]

Count matching nodes.

count(//car)

See also: