首页 文章

Xpath - 通过搜索以下兄弟节点来选择节点

提问于
浏览
1

我有这样的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 节点,这些节点在首先跟随-sibling h节点find下去的xml树时是 h1 节点 . 如果首先发现以下兄弟是 h2 ,则不应选择 h1 .

所以xml以上

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

应该选择节点 .

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

Xpath version is 2.0

1 回答

  • 3

    This is one possible XPath 1.0 compatible expression :

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

    brief explanation :

    • /chap/h1 :查找所有 h1 ,它是根元素的直接子元素 chap

    • following-sibling::*[starts-with(name(),'h')][1] :找到最近的兄弟元素 name()h 开头...

    • [self::h1] :...找到的元素是 h1

相关问题