XPath:一起选择自己和兄弟姐妹 [英] XPath: Select self and following sibling together

查看:307
本文介绍了XPath:一起选择自己和兄弟姐妹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆