Skip to main content
XMLDir

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

XPath axe

ancestor:: and ancestor-or-self::

Every node above the context, up to the root. Returned in reverse document order.

ancestor:: selects all containing elements up to and including the root node; ancestor-or-self:: adds the context node itself. It is the general form of parent::.

The axis is a reverse axis, which changes what positional predicates mean: ancestor::*[1] is the nearest ancestor, not the outermost.

Syntax
ancestor::name
Returns
node-set
Kind
Axe
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(//price/ancestor::*)on order.xmlRun
    5

    Five, not nine. Three prices have three ancestors each, but a node-set holds no duplicates: the three <line> elements are distinct, <lines> and <order> are shared.

  • name(//price[1]/ancestor::*[1])on order.xmlRun
    line

    [1] on a reverse axis is the nearest, not the outermost.

  • count(//price[1]/ancestor::lines)on order.xmlRun
    1

Run your own expression

What catches people out

  • It is a reverse axis: [1] means nearest. That catches people who expect document order.
  • ancestor::* includes the root element, so counts are one higher than the nesting depth you were picturing.

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.