XPath Basics
XPath is a query language purpose-built for navigating XML: instead of writing code to walk the document yourself, you write a path expression describing what you want, and a parser hands back the matching elements or attributes.
The document
Every example on this page queries the same small document:
<library>
<book id="1">
<title>Dune</title>
<price>12.99</price>
</book>
<book id="2">
<title>Foundation</title>
<price>9.99</price>
</book>
</library>
Absolute paths
A path starting with / begins at the document root and walks down through element names, exactly like a file path walks down through folders:
/library/book/title
<title>Dune</title> <title>Foundation</title>
Selecting an attribute
An @ prefix selects an attribute instead of a child element:
/library/book/@id
id="1" id="2"
Searching anywhere with //
A double slash matches an element anywhere in the document, regardless of how deeply it's nested — useful when you don't want to (or can't) spell out the full path:
//price
<price>12.99</price> <price>9.99</price>
Filtering with a predicate
Square brackets add a condition, filtering which matches actually get returned — either by position or by a value check:
/library/book[1]/title
<title>Dune</title>
/library/book[@id='2']/title
<title>Foundation</title>
book[1] is the first book, not the second. This trips up nearly everyone coming from a programming language, where zero-based indexing is the norm almost everywhere else.