Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 422
Gokul Avatar asked Feb 26 '19 15:02

Gokul


People also ask

What is difference between ancestor and parent?

An ancestor, also known as a forefather, fore-elder or a forebear, is a parent or (recursively) the parent of an antecedent (i.e., a grandparent, great-grandparent, great-great-grandparent and so forth). Ancestor is "any person from whom one is descended. In law, the person from whom an estate has been inherited."

What is parent in XPath?

In XPath, the parent node of the current node selected in the web page is retrieved using the Parent method. It comes in handy when we choose an element and need to utilise Xpath to fetch the parent element. This method can also be used to find out who the parent's parents are and abbreviated as (..).

What is the difference between child and descendant in XPath?

child:: are your immediate children. descendant:: are your children, and their children, recursively.


1 Answers

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::*.

like image 60
kjhughes Avatar answered Oct 07 '22 01:10

kjhughes