Gokul
Gokul

Reputation: 197

In XPath what is the difference between parent and ancestor?

I am seeing 2 different axis in XPath

  1. parent
  2. ancestor

Is ancestor[1] is equal to parent? i.e.,

//*[text()='target_text']//ancestor::div[1]

is equal to

//*[text()='target_text']//parent::div

Upvotes: 12

Views: 8848

Answers (1)

kjhughes
kjhughes

Reputation: 111531

The difference between parent:: and ancestor:: axis is conveyed by their names: A parent is the immediately direct ancestor.

So, for this XML for example,

<a>
  <b>
    <c>
      <d/>
    </c>
  </b>
</a>
  • /a/b/c/d/parent::* selects c
  • /a/b/c/d/ancestor::* selects c, b, and a

So, yes /a/b/c/d/ancestor::*[1] would be the same as /a/b/c/d/parent::*.

Upvotes: 18

Related Questions