Home > Software design >  How to read this xpath expression?
How to read this xpath expression?

Time:07-22

Can someone explain me please how to read this expression in xpath:
/a/b[3]/preceding-sibling::*[1]/d/@id ?
(My problem is mainly to understand this part: preceding-sibling::*[1])

In given the following xml document:

<a>
      <b> 
            <c ref="a5">2000</c>
            <d id="a3">3</d>
            <d id="a4">4</d> 
            <d id="a5">a</d> 
            <d id="a6">b</d>
             <f></f> 
      </b> 

      <b> 
            <c ref="a5">3000</c> 
            <f></f> 
            <d id="a7">7</d> 
            <d id="a8">8</d> 
            <d id="a9">9</d> 
      </b>

      <b> 
            <c ref="a6">4000</c>
             <f></f> 
      </b> 
</a>

Why it returns the following output:

Attribute='id=a7'
Attribute='id=a8'
Attribute='id=a9'

CodePudding user response:

It doesn't make a lot of sense in the context of your sample xml, but it means this:

/a/b[3]

find the third <b> child of <a> - the last <b> in this case.

/preceding-sibling::*[1]

find the child of <a> immediately (first) preceding that <b> child, regardless of its name. In this case, this (2nd) child also happens to be a <b>, so it's equivalent to /a/b[2], but whatever.

/d

find the <d> children of that <b> - there are 3 of them in the 2nd <b>. Finally,

/@id

Find the attribute value of the attribute id of these 3 children - and that's how you get your output.

  • Related