Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ancestor and ancestor-or-self

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.

like image 864
J_Coder Avatar asked Jun 21 '15 11:06

J_Coder


1 Answers

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" />'
like image 84
har07 Avatar answered Sep 22 '22 00:09

har07