Skip to main content

Search 400 pages — tools, formats, elements, namespaces, directory, comparisons, XPath, datatypes, glossary, parse errors, schema errors, use cases, guides, blog and product.

XPath guide

XPath first match vs first match per parent

Why //item[1] can return several nodes while (//item)[1] returns one, and how predicate context changes the result.

6 min read · Updated 2026-08-21

The short answer

//item[1] selects each item that is first among its item siblings, so it may return one per parent. (//item)[1] builds the complete node-set first and then selects its first member, so it returns at most one node for the document.

Predicates filter the step they follow

In //item[1], the predicate belongs to the item step. Each parent supplies its own item siblings and position 1 can be true more than once across the document.

Two parents, two first items
<catalog>
  <section id="a"><item>A1</item><item>A2</item></section>
  <section id="b"><item>B1</item><item>B2</item></section>
</catalog>
First item under every section
//item[1]

Returns A1 and B1.

Parentheses change what gets filtered

Parentheses make //item produce one document-ordered node-set before [1] runs. The predicate then sees four nodes in one context and keeps only A1.

First item in the document
(//item)[1]

Returns A1 only.

Last item in the document
(//item)[last()]

Returns B2 only.

State the scope in plain language first

Before writing the expression, say whether you mean one result for the whole document, one result per parent, or the first parent that contains a match. Those are different queries, and brackets alone do not communicate which scope you intended.

  • Whole document: (//item)[1]
  • Per parent: //section/item[1]
  • First section's first item: (//section)[1]/item[1]
  • First matching item by value: (//item[.='B1'])[1]

Get started

Bring order to the XML your team can't afford to ignore.

Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.