我知道XPath中的祖先,但是什么是ancestor-or-self?在什么情况下需要使用它?请给我一些示例。
我认为轴名称相当自解释。ancestor
轴仅选择当前上下文元素的祖先,而 ancestor-or-self
选择包括当前元素在内的祖先。例如,请考虑以下 XML:
<root>
<item key="a">
<item key="b" target="true">
<context key="c" target="true"/>
</item>
</item>
</root>
以下xpath使用了ancestor
轴,将会找到具有target
属性等于true
的项目b
,因为b
是context
元素的祖先。但是该XPath不会选择context
元素本身,尽管它也具有target
等于true
://context/ancestor::*[@target='true']
在XPath测试器中,上述XPath的输出结果为:
Element='<item key="b" target="true">
<context key="c" target="true" />
</item>'
与ancestor-or-self
轴相反,它会返回相同的结果,并包括context
元素:
//context/ancestor-or-self::*[@target='true']
第二个XPath的输出:
Element='<item key="b" target="true">
<context key="c" target="true" />
</item>'
Element='<context key="c" target="true" />'