Search code examples
xmlxpathxpath-1.0

How to get first 2 siblings after the match using Xpath1.0?


I have the below xml:

<book>
  <name id="11" />
  <name id="12" />
  <name id="13" />
  <name id="51" />
  <name id="18" />
  <name id="61" />
  <name id="198" />
  <name id="41" />
</book>

I wrote the below Xpath :-

/book/*[@id=51]/following-sibling::*

Getting output as :

<name id="18"/>
<name id="61"/>
<name id="198"/>
<name id="41"/>

My goal is to get only :

<name id="18"/>
<name id="61"/>

I want to select first 2 siblings after the match. How to do that ?


Solution

  • Does position() do what you require?

    /book/*[@id=51]/following-sibling::*[position()<=2]