最好通过一个简化的示例来展示:
<?xml version="1.0" encoding="utf-8"?>
<root>
<A name="wrong"></A>
<B>not this</B>
<A name="right">
<subA></subA>
</A>
<B>yes, this</B> <!-- I want only this one -->
<A name="right">
<subA></subA>
</A>
<C>dont want this</C>
<B>not this either</B> <!-- not immediately following -->
</root>
我想要获取所有在 <A>
节点中,具有 name
属性等于 "right"
的节点后紧随其后的 <B>
节点。
我的尝试:
//A[@name="right"]/following-sibling::*[1]
这个选择器选中了紧接在 "right" <A>
之后的任何节点(包括 <C>
)。我不知道如何只选中 <B>
。以下方式无法实现:
//A[@name="right"]/following-sibling::*[1 and B]
这个:
这个:
//A[@name="right"]/following-sibling::B[1]
将选择在“right” <A>
后的第一个<B>
,但不一定是紧接着的那个。
//A[@name='right']/following-sibling::*[1][self::B]
,部分原因是为了简洁,另一部分原因是在命名空间存在的情况下,self::B
是一个更准确的测试。 - Michael Kay