Xml/Xslt - get node with highest attribute value

Asked By Roulf Bhan on 21-Jul-14 01:14 PM
I have an xml loaded into dom. I want to do selectnode or something similar to get the node with the highest attribute value.

For e.g i want the node with val=100
<root>
<node val=100/>
<node val=22/>
..
..
<node val=99>
</root>

Unfortunately - Asked By Peter Bromberg on 25-Jan-02 01:09 PM

If you have been looking for a "max" function in the Math functions of XPATH, there is none. You could use XSLT as follows:
<!-- Iterate over a descending node-set -->
<xsl:for-each select="closing-price">
<xsl:sort data-type="number" select="@mid" order="descending"/>

<!-- Choose only the first node (ie largest) -->
<xsl:if test="position()=1">
<xsl:variable name="MaxValue" select="@mid" />

<!-- Now iterate over the list again in original sort order -->
<xsl:for-each select="closing-price">

<!-- Do Something with $MaxValue -->

</xsl:for-each>


</xsl:if>
</xsl:for-each>

--- the other alternative would be to get a NodeList with SelectNodes, then iterate over it using a script min / max
routine until the position of the highest attribute value has been determined.