Saturday, December 09, 2006

Work around for math:max in XPath 1.0

XPath 1.0 doesn't provide the function max(), but the function last() behaves differently with numerical parameters.

For example:


<?xml version="1.0" encoding="UTF-8"?>
<nodes>
<node name="1" value ="2"></node>
<node name="2" value = "3"></node>
<node name="3" value = "1"></node>
<node name="4" value = "5"></node>
<node name="5" value = "4"></node>
</nodes>

has nodes with different values. To find the maximum of the values available, we can use the last method as follows:


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="nodes">
Max value - <xsl:value-of select="node/@value[last()]"/>
</xsl:template>
</xsl:stylesheet>

The function last() finds the max value of an attribute in a given node-set. This function can be used as a workaround if we are not using XPath 2.0.

But the last() function is normally used to find the position of the last node.

No comments: