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

Using XPATH to find elements with a certain attribute

I have the following XML document. I want to build a query in XPath to find all the Ship elements for the Ships that were launched before 1917

 <Ships>
    <Class name="Kongo">
    <Ship name="h" launched="1915"/>
    <Ship name="h1" launched="1920"/>
    </Class>
    
    <Class name="Kongo2">
    <Ship name="h2" launched="1941"/>
    <Ship name="h3" launched="1941"/>
    </Class>
    <Class name="Kongo2">
    <Ship name="h4" launched="1917"/>
    <Ship name="h5" launched="1917"/>
    </Class>
    
    </Ships>

I came up with the following Xpath : if(/Ships/Class/Ship/number(@launched) < 1917) then Ships/Class/Ship else ()
But this lists down all the Ship elements even though the if check is there. What could be wrong with this?

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

>Solution :

You can use a predicate like this (only XPath-1.0 required):

/Ships/Class/Ship[1917 > @launched]

The predicate expression is inverted to avoid the less than char < which is problematic in some contexts. But the semantic stays the same as in @launched < 1917.

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