1

What is the difference between the following two XPath expressions?

//Title
descendant::Title

Are they both the exact same, or is there any difference in how they operate?

kjhughes
  • 98,039
  • 18
  • 159
  • 218
David542
  • 101,766
  • 154
  • 423
  • 727

1 Answers1

4

Difference:

  • // is short for /descendant-or-self::node()/, and the descendant-or-self:: axis includes the context item.
  • The descendant:: axis does not include the context item.

So for this XML, assuming the default context item1 is the root element (the outer Title element),

<Title id="t1">
  <Title id="t2"/>
</Title>
  • //Title selects both Title elements (id="t1" and id="t2")

  • descendant::Title selects only the inner Title element (id="t2")

Unasked but noteworthy:

  • /descendant::Title selects both Title elements (id="t1" and id="t2")

The difference between /descendant::Title and //Title manifests only if Title were to have a positional predicate. See Differences between // and /descendant in XPath selecting multiple children for further details.


1 Default context item note

Thanks to Michael Kay for pointing out the importance of explicitly stating the context item here. Elaborating...

Some XPath tools (e.g: oXygen XML) default the context item to the root element (the outer Title, here); other XPath tools (e.g: XPather.com) default the context item to the root node. If the context item is the root node, descendant::Title also will select both Title elements.

See also

kjhughes
  • 98,039
  • 18
  • 159
  • 218
  • Surely this is only true if the context item is the outer `Title` element? If the context item is the document node, `descendant::X` and `//X` have exactly the same effect - though as you say, positional predicates behave differently. – Michael Kay Dec 01 '20 at 09:01
  • @MichaelKay: Correct, answer updated to call out the importance of the default context item. Thank you! – kjhughes Dec 01 '20 at 14:36