Skip to main content
XMLDir

Search 169 pages — formats, namespaces, parser messages, schema errors and tools.

XPath function

position()

The one-based index of the context node. [n] is shorthand for [position() = n].

position() returns where the context node sits in the node list being processed, counting from 1. A numeric predicate is shorthand for comparing against it: [2] and [position() = 2] are the same expression.

It becomes useful the moment you need a range rather than a single index — [position() <= 2] takes the first two.

Syntax
position() → number
Returns
number
Kind
Function
Version
XPath 1.0 (libxml2)

Worked examples

Each result below is what the evaluator returned, asserted on every test run. An empty result means an empty node-set — which is an answer, not an error.

  • //line[2]/@skuon order.xmlRun
     sku="WIDGET-2"
  • count(//line[position() <= 2])on order.xmlRun
    2
  • count(//line[position() > 1])on order.xmlRun
    2

Run your own expression

What catches people out

  • Positions start at 1. [0] is valid syntax and selects nothing, which is why it fails silently rather than loudly.
  • [1] is not 'the first node in the document' — it is the first in each context, so //line[1] can select several nodes if there are several parents.
  • In XPath 1.0 you cannot write //line[position() = 2 or 3] and mean what you hoped; 3 is a bare number, which is true. Write [position() = 2 or position() = 3].

The sample documents

Every example on this page runs against this document. The sitemap one is namespaced on purpose — almost every real XML document is, and that changes which expressions match.

order.xml
<?xml version="1.0" encoding="UTF-8"?>
<order id="A-1001" tier="gold">
  <customer country="NO">Ada Lovelace</customer>
  <lines>
    <line sku="WIDGET-1" qty="2"><price>14.50</price></line>
    <line sku="WIDGET-2" qty="1"><price>39.00</price></line>
    <line sku="GIFT-WRAP" qty="1"><price>0.00</price></line>
  </lines>
  <note>  Deliver after 09:00  </note>
</order>

Related

All 34 XPath entries

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.