XPath Cheatsheet - XML/HTML Selector Syntax Reference

All essential XPath commands organized by use case, with 34+ entries you can copy and run directly. Find the right command fast when you need it.

Dev Tools·34 commands·Last updated 2026-07-21
Back to Dev Tools

Basic Paths 7

/
从根节点选取
//
从任意位置选取(recursively)
.
当前节点
..
父节点
/bookstore/book
根下 bookstore 的 book 子元素
//book
文档中所有 book 元素
book/title
book 下的 title 子元素

Predicate Filtering 6

//book[1]
第一个 book
//book[last()]
最后一个 book
//book[position()<3]
前两个 book
//book[@lang="zh"]
lang property为 zh 的 book
//book[price>35]
price 大于 35 的 book
//book[title]
含有 title 子元素的 book

Axes 7

ancestor::div
所有祖先 div
parent::node()
父节点
child::title
子节点 title
descendant::p
所有后代 p
following-sibling::div
后的兄弟 div
preceding-sibling::h2
前的兄弟 h2
self::a
自身(当且仅当是 a 时)

Common Functions 8

contains(@class, "active")
class propertypackage含 active
starts-with(text(), "Hello")
文本以 Hello beginning
normalize-space()
去除首尾空白&Compress中间空白
string-length(text())
文本length
count(//book)
book 元素总数
concat("a", "-", "b")
stringconcat
substring("hello", 1, 3)
slice子串
translate("abc", "abc", "ABC")
字符Replace

Glob & Operations 6

*
Match任意元素节点
@*
Match任意property
node()
Match任意type节点
//a | //b
a 和 b 的&集
//div[@id="x" and @class="y"]
and condition
//div[@class="a" or @class="b"]
or condition

💡 Tips

  • // 比 / 慢很多,大范围文档优先用精确路径。
  • contains(@class, "x") 会匹配 "x y" 这种复合 class,比精确匹配更实用。
  • XPath 1.0 不支持正则,需要正则匹配得上 XPath 2.0 或用 contains 组合。

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

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

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it