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.
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" />'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With