XPath:限制结果集的范围 [英] XPath: limit scope of result set
问题描述
给定 XML
<a>
<c>
<b id="1" value="noob"/>
</c>
<b id="2" value="tube"/>
<a>
<c>
<b id="3" value="foo"/>
</c>
<b id="4" value="goo"/>
<b id="5" value="noob"/>
<a>
<b id="6" value="near"/>
<b id="7" value="bar"/>
</a>
</a>
</a>
和 Xpath 1.0 查询
and the Xpath 1.0 query
//b[@id=2]/ancestor::a[1]//b[@value="noob"]
上面的 Xpath 返回节点 id 1 和 5.目标是将结果限制为节点 id=1,因为它是唯一的 @value="noob"
元素的后代相同 的 (
//b[@id=2]
) 也是其后代.
The Xpath above returns both node ids 1 and 5. The goal is to limit the result to just node id=1 since it is the only @value="noob"
element that is a descendant of the same <a>
that (//b[@id=2]
) is also a descendant of.
换句话说,查找所有值为noob"的 b 元素,它们是 a 元素的后代,该元素也有一个 id 为 2 的后代,但是不是任何其他 a 元素的后代".怎么这么纠结?实际上,id 编号和值是可变的,并且会有数百种节点类型.
In other words, "Find all b elements who's value is "noob" that are descendants of the a element which also has a descendant whose id is 2, but is not the descendant of any other a element". How's that for convoluted? In practice the id number and values would be variable and there would hundreds of node types.
如果 id=2,我们希望返回元素 id=1 而不是 id=5,因为它包含在另一个 a 元素中.如果 id=4,我们希望返回 id=5,但不会返回 id=1,因为它不在第一个祖先元素中作为 id=4.
If the id=2, we would expect to return element id=1 not id=5 since it is contained in another a element. If the id=4, we would expect to return id=5, but not id=1 since it is not in the first ancestor a element as id=4.
根据 Dimitre 和 Alejandro 的评论,我找到了这个有用的博客说明 count() 与 | 一起使用的条目union 运算符以及其他一些很好的技巧.
Based on the comments of Dimitre and Alejandro, I found this helpful blog entry explaining the use of count() with the | union operator as well as some other excellent tips.
推荐答案
使用:
//b[@value='noob']
[count(ancestor::a[1] | //b[@id=2]/ancestor::a[1]) = 1]
说明:
第二个谓词确保两个 b
元素具有相同的最近祖先 a
.
The second predicate assures that both b
elements have the same nearest ancestor a
.
记住:在 XPath 1.0 中,节点身份的测试是:
Remember: In XPath 1.0 the test for node identity is:
count($n1 | $n2) = 1
这篇关于XPath:限制结果集的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!