Home > Blockchain >  Using XPATH to find elements with a certain attribute
Using XPATH to find elements with a certain attribute

Time:03-15

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?

CodePudding user response:

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.

  • Related