XPath Cheatsheet - XML/HTML Selector Syntax Reference

Regex is the wrong tool for pulling nodes out of XML/HTML — XPath was built for it. This reference covers node paths, predicate filters, axis navigation, string/functions and wildcards, with the scraping cases you actually meet. Use it when scraping a page, querying an XML config or asserting in tests, instead of writing fragile regex that breaks on whitespace. After reading you write a selector that targets exactly the node you want, including positions and attributes.

Dev Tools·34 commands·Last updated 2026-07-21
xpathxmlhtmlWeb Scraping

Basic Paths 7

/
Select from the root node
//
Select from anywhere (recursive)
.
Current node
..
Parent node
/bookstore/book
book child of bookstore under root
//book
All book elements in the document
book/title
title child of book

Predicate Filtering 6

//book[1]
First book
//book[last()]
Last book
//book[position()<3]
First two books
//book[@lang="zh"]
book whose lang attribute is zh
//book[price>35]
book with price > 35
//book[title]
book containing a title child

Axes 7

ancestor::div
All ancestor div
parent::node()
Parent node
child::title
Child node title
descendant::p
All descendant p
following-sibling::div
Following sibling div
preceding-sibling::h2
Preceding sibling h2
self::a
Self (only if it is a)

Common Functions 8

contains(@class, "active")
class attribute contains active
starts-with(text(), "Hello")
Text starts with Hello
normalize-space()
Trim leading/trailing and collapse inner whitespace
string-length(text())
Text length
count(//book)
Total number of book elements
concat("a", "-", "b")
Concatenate strings
substring("hello", 1, 3)
Substring
translate("abc", "abc", "ABC")
Character replacement

Wildcards & Operators 6

*
Match any element node
@*
Match any attribute
node()
Match any node type
//a | //b
Union of a and b
//div[@id="x" and @class="y"]
and condition
//div[@class="a" or @class="b"]
or condition

Tips

  • // is much slower than /; prefer exact paths for large documents.
  • contains(@class, 'x') matches composite classes like 'x y', more practical than exact match.
  • XPath 1.0 has no regex; for regex matching use XPath 2.0 or combine with contains.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us