Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read this xpath expression?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading