David542
David542

Reputation: 110153

descendants:: vs // in XPath

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?

Upvotes: 1

Views: 461

Answers (1)

kjhughes
kjhughes

Reputation: 111531

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

Upvotes: 4

Related Questions