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

Get the position of an element with specific attribute value

I’m trying to get with xPath the position only of the first element which has the attribute value true.

<?xml version="1.0" encoding="UTF-8"?>
<elements>
    <element attribute="false"/>
    <element attribute="true"/>
    <element attribute="true"/>
</elements>

What I have so fare is:

 head(/elements/element[@attribute='true']/position())

Result:

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

 1

But it should be:

 2

What am I doing wrong?

>Solution :

position() returns the position of the element in the nodelist created by the predicate, i.e. with the false excluded. Instead of position, you can e.g. count the number of preceding elemements.

For example, this works even in XPath 1.0:

1+count(/elements/element[@attribute="true"][1]/preceding-sibling::element)
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