Reputation: 737
I know about ancestor in xpath but what is this ancestor-or-self. when we have to use ancestor-or-self.Please give me any examples.
Upvotes: 7
Views: 15605
Reputation: 2291
Ancestor and Ancestor-or-self are the XPath Axes. An axis is a node-set relative to the current node.
The ancestor axis selects all the ancestors, i.e. parent, grandparent, etc of the current node whereas the ancestor-or-self selects all the ancestors, i.e. parent, grandparent, etc. of the current node and the current node itself.
Ancestor-or-self is generally used to locate the XML document tags or in XSLT that is a transformation language for XML designed to transform structured documents into other formats (such as XML, HTML, and plain text).
I believe that you may not need these axes to find the XPath in Selenium Webdriver as it deal with HTML tags not the XML tags and there are many other XPath axes that may help in finding the elements.
Upvotes: 2
Reputation: 89285
The axis name is quite self-explanatory I think. ancestor
axis selects only ancestor(s) of current context element, while ancestor-or-self
selects both ancestor(s) and the current element itself. Consider the following XML for example :
<root>
<item key="a">
<item key="b" target="true">
<context key="c" target="true"/>
</item>
</item>
</root>
The following xpath which uses ancestor
axis, will find the item b
because it has target
attribute equals true
and b
is ancestor of context
element. But the XPath won't select context
element itself, despite it has target
equals true
:
//context/ancestor::*[@target='true']
output of the above XPath in xpath tester :
Element='<item key="b" target="true">
<context key="c" target="true" />
</item>'
contrasts with ancestor-or-self
axis which will return the same, plus context
element :
//context/ancestor-or-self::*[@target='true']
output of the 2nd XPath :
Element='<item key="b" target="true">
<context key="c" target="true" />
</item>'
Element='<context key="c" target="true" />'
Upvotes: 14