我有一份文件,如下:
<root>
<A node="1"/>
<B node="2"/>
<A node="3"/>
<A node="4"/>
<B node="5"/>
<B node="6"/>
<A node="7"/>
<A node="8"/>
<B node="9"/>
</root>
使用xpath,如何选择连续跟随给定A元素的所有B元素?
它类似于跟随-silbing :: B,除了我希望它们只是紧随其后的元素 .
如果我在A(节点== 1),那么我想选择节点2.如果我在A(节点== 3),那么我想什么都不选 . 如果我在A(节点== 4),那么我想选择5和6 .
我可以在xpath中执行此操作吗?编辑:它在XSL样式表选择语句中 .
EDIT2:我没有't want to use the node attribute on the various elements as a unique identifier. I included the node attribute only for purposes of illustrating my point. In the actual XML doc, I don't有一个我用作唯一标识的属性 . 节点属性上的xpath "following-sibling::UL[preceding-sibling::LI[1]/@node = current()/@node]"键,这不是我想要的 .
3 回答
简短回答(假设current()没问题,因为这是标记的xslt):
样式表示例:
祝好运!
虽然@Chris Nielsen的答案是正确的方法,但在比较属性不是唯一的情况下会留下不确定性 . 解决这个问题的更正确的方法是:
这确保
preceding-sibling::A
与当前A
相同,而不是仅仅比较某些属性值 . 除非您拥有保证唯一的属性,否则这是唯一安全的方法 .解决方案可能是首先使用
following-sibling::*
收集所有以下节点, grab 第一个节点并要求它为'B'节点 .