How to find the max attribute from an XML document using Xpath 1.0

HerbSpiral picture HerbSpiral · Jan 2, 2012 · Viewed 33.9k times · Source

Is there a way to query an XML document to return the maximum of a given attribute using Xpath 1.0 ?

For example is there a way to get the max id ?

<?xml version="1.0" encoding="utf-8"?>
<library>
        <book id="2" name="Dragon Tatoo"/>
        <book id="7" name="Ender's Game"/>
        <book id="3" name="Catch 22"/>
        <book id="1" name="Lord of the rings"/>
</library>

Answer

Fred Foo picture Fred Foo · Jan 2, 2012

In XPath 2.0, use the max function. To find the book with the highest id, do

/library/book[@id = max(/library/book/@id)]