Skip to main content
XMLDir

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

XPath operator

Predicates [ ]

Filters a node-set. Order matters, and a numeric predicate is not the same as a positional one applied afterwards.

A predicate filters the node-set produced by its step. Multiple predicates apply left to right, each filtering the result of the last, so [@qty='1'][1] and [1][@qty='1'] can differ.

A number is shorthand for a position test. Anything else is converted to a boolean, which means [@sku] tests for the attribute's presence rather than its value.

Syntax
step[expression]
Returns
node-set
Kind
Operator
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.

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

    Filter first, then take the first of what remains.

  • count(//line[1][@qty = '1'])on order.xmlRun
    0

    The other order: take the first line, then test it — and it does not match.

  • count(//line[@sku])on order.xmlRun
    3

    Presence, not value: every line has a sku.

Run your own expression

What catches people out

  • [a][b] is not [a and b] when either is positional. Order changes the result.
  • [0] is legal and selects nothing, because positions start at 1.
  • //line[1] is 'the first line under each parent', not 'the first line in the document'. For that, wrap it: (//line)[1].

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.