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:

XML library.xml
<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:

XPath /library/book/title
/library/book/title
Matches
<title>Dune</title>
<title>Foundation</title>

Selecting an attribute

An @ prefix selects an attribute instead of a child element:

XPath /library/book/@id
/library/book/@id
Matches
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:

XPath //price
//price
Matches
<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:

XPath by position
/library/book[1]/title
Matches
<title>Dune</title>
XPath by attribute value
/library/book[@id='2']/title
Matches
<title>Foundation</title>
Note: XPath indexing starts at 1, not 0 — 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.