【问题标题】:Xpath - Select nodes by searching following siblingsXpath - 通过搜索以下同级来选择节点
【发布时间】:2015-12-29 06:17:50
【问题描述】:

我有一个这样的xml,

<chap>
    <p>aaa</p>
    <h1>bbb</h1>
    <p>ccc</p>
    <p>ddd</p>
    <h1>eee</h1>
    <p>fff</p>  
    <h2>ggg</h2> 
    <p>hhh</p> 
    <h1>iii</h1> 
    <p>jjj</p> 
    <h1>kkk</h1> 
    <p>lll</p> 
    <h1>mmm</h1> 
    <p>nnn</p> 
    <h2>ooo</h2> 
    <h1>ppp</h1>
    <p>qqq</p>
</chap>

我需要选择h1 节点,当沿着xml 树向下第一个follow-sibling h 节点时找到的是h1 节点。如果第一次找到following-sibling 是h2,则不应选择h1

所以上面的xml

<h1>bbb</h1>
<h1>iii</h1>
<h1>kkk</h1> 

应该选择节点。

如何编写 xpath 查询以从 xml 中选择上述节点?

Xpath version is 2.0

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    这是一种可能的 XPath 1.0 兼容表达式:

    /chap/h1[following-sibling::*[starts-with(name(),'h')][1][self::h1]]
    

    简要说明:

    • /chap/h1 :查找所有 h1 即根元素 chap 的直接子元素
    • following-sibling::*[starts-with(name(),'h')][1] :找到最近的以name() 开头的兄弟元素以h...
    • [self::h1] : ... 找到的元素是 h1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 2011-04-10
      相关资源
      最近更新 更多