XPath:一起选择自己和兄弟姐妹 [英] XPath: Select self and following sibling together
问题描述
< DIV>
< dt>
测试1
< / dt>
< dd>
< / dd>
< dt>
测试2
< / dt>
< dd>
< / dd>
< / div>
到目前为止我写了这个XPath
// dt [contains(text(),Test)] / self :: dt | following-sibling :: dd
但是,这并不是带来 dt 和 dd ,而是 dt 。
如果它必须是单个XPath 1.0表达式,那么您必须说
// dt [contains(。,'Test')] | // dt [contains(。,'Test')] / following-sibling :: dd [1]
<最后的 [1]
非常重要,因为它不会提取包含Test的dt之后的所有 em元素,即给定
< div>
< dt>
测试1
< / dt>
< dd>
Foo
< / dd>
< dt>
其他2
< / dt>
< dd>
Bar
< / dd>
< / div>
没有 [1]
的版本会匹配三个节点,包含测试1和em的 dt
Foo和Bar dd code>元素。
[1]
您只能正确地获得Test 1和Foo。
但是,根据您使用XPath的具体情况,首先选择
// dt [contains(。,'Test')]
然后遍历节点匹配,并评估
。 |在每个这些节点的上下文中依次 - sibling :: dd [1]
。 / p>
<div>
<dt>
Test 1
</dt>
<dd>
</dd>
<dt>
Test 2
</dt>
<dd>
</dd>
</div>
I have this XPath written so far
//dt[contains(text(), "Test")]/self::dt|following-sibling::dd
But this is not bringing both dt and dd but just dt.
If it must be a single XPath 1.0 expression then you'll have to say
//dt[contains(., 'Test')] | //dt[contains(., 'Test')]/following-sibling::dd[1]
The final [1]
is important, as without that it would extract all dd elements that follow a dt containing "Test", i.e. given
<div>
<dt>
Test 1
</dt>
<dd>
Foo
</dd>
<dt>
Something else 2
</dt>
<dd>
Bar
</dd>
</div>
the version without the [1]
would match three nodes, the dt
containing "Test 1" and both the "Foo" and "Bar" dd
elements. With the [1]
you would correctly get only "Test 1" and "Foo".
But depending on exactly how you're using the XPath it may be clearer to first select
//dt[contains(., 'Test')]
and then iterate over the nodes that this matches, and evaluate
. | following-sibling::dd[1]
in the context of each of those nodes in turn.
这篇关于XPath:一起选择自己和兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!