XPath //item[1] vs (/descendant::item)[1] Explained
In XML querying, //item[1] and
(/descendant::item)[1] appear similar but yield completely
different results due to operator precedence. While
//item[1] selects the first item child of
every matching parent element across the document,
(/descendant::item)[1] collects all item
elements in the entire document into a single sequence and returns only
the very first one.
Operator Precedence and Expansion
The key distinction lies in how XPath evaluates step expressions versus parenthesized expressions.
The expression //item[1] expands to:
/descendant-or-self::node()/child::item[1]
In XPath, the predicate [1] has a higher precedence than
the // shorthand. The predicate attaches directly to the
relative step child::item, evaluating the position relative
to the context of each immediate parent node. Consequently, it selects
any <item> element that is the first
<item> child within its respective parent.
In contrast, the expression (/descendant::item)[1] uses
parentheses to override default operator precedence. The inner
expression /descendant::item first searches the entire
document and gathers all <item> elements into a
single node set in document order. The predicate [1] is
then applied globally to that entire collection, returning exclusively
the first node.
Practical Example
Consider the following XML document:
<store>
<category name="electronics">
<item>Laptop</item>
<item>Phone</item>
</category>
<category name="books">
<item>Novel</item>
<item>Dictionary</item>
</category>
</store>Applying the two XPath queries yields the following:
//item[1]returns two nodes:<item>Laptop</item>(the firstitemchild inside theelectronicscategory)<item>Novel</item>(the firstitemchild inside thebookscategory)
(/descendant::item)[1]returns one node:<item>Laptop</item>(the firstitemfound in the entire document)
Key Takeaway
Use //item[1] when you need the first matching child
within each parent context, and use (/descendant::item)[1]
(or (//item)[1]) when you need strictly one result
representing the absolute first match in document order.