XPaths Explained With Paths, Predicates, and Real Results

XPath expressions and XPath selection patterns compared on an XML tree with position predicates.

An expression that looks right can return no nodes, or more nodes than expected, when its starting point or predicate is misunderstood. Read an XPath as a path through a tree: identify the context node, follow each step, and then apply the filters. The XPath selection examples below use one small XML document so every result can be checked.

XPath Selectors on a Small XML Tree

Use this document for the examples. It has no namespaces, and the initial context node is the document node, above <library>, unless a section specifies otherwise:

<library>
  <shelf name="north">
    <book id="b1"><title>Blue Sky</title><price>12</price></book>
    <book id="b2"><title>Green Earth</title><price>18</price></book>
  </shelf>
  <shelf name="south">
    <book id="b3"><title>Blue Sea</title><price>15</price></book>
    <book id="b4"><title>Night Sky</title><price>22</price></book>
  </shelf>
</library>

XPath selectors describe nodes or values relative to a context. /library/shelf/book starts at the document root and selects the four book elements. /library/shelf selects two shelf elements. The slash separates steps; it does not itself mean “search anywhere.”

The XPaths in this article use XPath 1.0 syntax. Some return a node-set, while functions such as count() return a number. How results are displayed depends on the tool, so results below identify nodes by their id or give the actual scalar value. The XPath 1.0 specification defines these expressions and their context.

Follow paths and axes

From the document node, //book selects b1, b2, b3, and b4. The double slash is shorthand for steps that search through descendants; it is not a literal element name. An XPath expression such as /library/shelf/book/title selects all four title elements, not just their text nodes.

Now change the context node to the shelf whose name is north. The relative path book/title selects the titles of b1 and b2. ./book selects those two books from that same context. By contrast, an expression beginning with / starts from the document root, even if evaluation began at a shelf. This distinction is essential when XPath selectors are evaluated inside a previously selected component.

An axis makes the relationship explicit. From the book node b2, parent::shelf selects the north shelf; following-sibling::book selects no nodes because b2 is already its last book. From b1, that same sibling step selects b2. child::title selects the current book’s title; the shorter title uses the child axis implicitly.

These XPaths follow structure rather than a visual layout. A new wrapper inserted between a shelf and its books can break a direct child path even if the page or document looks unchanged. Choose a direct or descendant step because it expresses the relationship you need, not merely because one happens to match the sample. XPaths that rely on stable attributes can be easier to maintain when intermediate containers change.

Filter by attribute or text

Return to the document node as context. //book[@id='b3'] selects b3; @id refers to its attribute. //shelf[@name='north']/book selects b1 and b2. To select attribute nodes themselves, //book/@id returns the four id attributes in document order, whose values are b1 through b4.

The expression //book[title='Blue Sky'] selects b1. Its predicate compares the string value of the child title with the supplied text. //book/title/text() selects the title text nodes, while //book/title selects the elements containing them. In this sample each title has one simple text node; nested markup can make text-node selection and an element’s string value differ.

Functions can refine an XPath selection. //book[contains(title, 'Blue')] selects b1 and b3; the comparison is case-sensitive. count(//book) returns the number 4. normalize-space(' Blue Sky ') returns the string Blue Sky, trimming the ends and collapsing the internal whitespace. The result types matter: a number is not a collection of matching nodes. An XPath query returning a scalar must be read using the result type expected by its host tool.

Understand positions and parentheses

XPath positions start at 1. From the document node, //book[1] selects b1 and b3: it finds book elements that are the first book child of their respective parents. By contrast, (//book)[1] selects only b1, the first node in the combined result in document order. The parentheses change where the predicate is applied.

Similarly, /library/shelf[2]/book[1] selects b3: the first book under the second shelf. /library/shelf/book[2] selects b2 and b4, the second book under each shelf. These examples give the XPath selectors a stable tree and context, so the difference is visible rather than hidden in a large document.

Position filters on reverse axes deserve particular care. From b2, preceding-sibling::book[1] selects the nearest preceding book, b1. A parenthesized node-set can change how a subsequent positional filter is evaluated. When the exact neighbor matters, test the expression against a tree with several siblings and check the axis direction in the specification.

Compare XPath with CSS selectors

CSS selectors are commonly used to style or find elements in an HTML document. They are often concise for matching a tag, class, or attribute, such as book[id="b3"] in an appropriate document. XPath can also select attribute and text nodes, traverse axes such as parent, and return scalar results such as a count. The two languages have different syntax and capabilities; an expression from one cannot simply be pasted into the other.

For browser automation, choose a locator that expresses a stable relationship in the document. A unique, meaningful attribute can be more robust than a long chain of positions. If a positional XPath points to the third item, inserting another item before it may silently change the match. Inspect the actual DOM at the moment the tool evaluates the expression, especially when a page renders content asynchronously.

Diagnose an empty or surprising result

Start with the context node and simplify the path one step at a time. Confirm element and attribute names, capitalization in XML, and whether a direct child step should instead search descendants. Then inspect each predicate: is its position applied per parent or to the combined result? Check whether the tool expects nodes, text, or a scalar value.

If the document uses namespaces, an unprefixed element name in an XPath 1.0 expression may not match namespaced elements. Bind an expression prefix to the correct namespace URI using the tool’s namespace resolver. Finally, confirm the XPath version and the document state. Those checks turn an empty result into a specific mismatch you can reproduce and fix.