XPath get element by name with highest number value

Viewed 73

I have this xml source:

    <element1>
       <element2>
           <element3>156</element3>
           <element4>Test</element4>
           <element5>descriptionxxxx</element5>
       </element2>
       <element2>
           <element3>25</element3>
           <element4>Top</element4>
           <element5>descriptionyyyy</element5>
       </element2>
       <element2>
           <element3>852</element3>
           <element4>Test</element4>
           <element5>descriptionzzzz</element5>
       </element2>
   </element1>

I would need to find all element2 where element4 = "Test", and return element5 for the max of element3.(in this case, It would return "descriptionzzzz")

I have tried: To get all element2 with element4 = "Test" -> doc("xxx.xml")//element1/element2[element4="Test"]

But now I would need to get the element2 with the highest element3 of the previous list, and return element5 of that element2.

Thanks!

2 Answers

I have done something like this for my xml and it has worked for me: //element2[element4="Test"][element3=max(//element2[element4="Test"]/element3)]/element5

If you're able to use Saxon (PE or higher) there's an XPath extension function that does exactly what you need:

saxon:highest(//element2, function($e){number($e/element3)})

saxon:highest(S, F) finds the item(s) from S that have the highest value for the result of computing function F.

Related