1

I have a xml like this,

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

I need to select h1 nodes which when going down the xml tree first following-sibling h node find is h1 node. if first finding following-sibling is h2 that h1 should not be selected.

so above xml

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

nodes should be selected.

How can I write a xpath query to select above nodes from xml?

Xpath version is 2.0 

1 Answer 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 : find all h1 that is direct child of the root element chap
  • following-sibling::*[starts-with(name(),'h')][1] : find the nearest following sibling element having name() starts with h...
  • [self::h1] : ... and the found element is h1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.