How can I use XPath to find the minimum value of an attribute in a set of elements?

Solution 1:

Here's a slightly shorter solution.

Maximum:

/foo/bar/@score[not(. < ../../bar/@score)][1]

Minimum:

/foo/bar/@score[not(. > ../../bar/@score)][1]

I've edited the predicate so that it's applicable to any sequence of bar, even if you decide to change the path. Note that parent of attribute is the element to which it belongs.

If embedding these queries in XML files like XSLT or ant scripts, remember to encode < and > as &lt; respecting &gt;.

Solution 2:

Turns out the tool does not support XPath 2.0.

XPath 1.0 doesn't have the fancy min() and max() functions, so to find these values we need to be a little tricky with the XPath logic, and compare the values on the siblings of the node:

Maximum:

/foo/bar[not(preceding-sibling::bar/@score >= @score) 
    and not(following-sibling::bar/@score > @score)]/@score

Minimum:

/foo/bar[not(preceding-sibling::bar/@score <= @score) 
    and not(following-sibling::bar/@score < @score)]/@score

If embedding these queries in XML files like XSLT or ant scripts, remember to encode < and > as &lt; respecting &gt;.