How to display minimum and maximum values in HTML table using XSLT?
This example shows how to sort a list of numbers, then display only the highest and lowest values in a table.
These values can be determined as the first and last elements of an already sorted list. If no order is specified, the default sortorder is ascending. ie. numbers will start from the smallest.
The first and last nodes's values can be displayed by using
<xsl:if> and the
position() XPath function.
Create an XML document and link it to a XSL stylesheet.
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sort_min_max.xsl"?>
<root>
<number>
<digit>5</digit>
</number>
<number>
<digit>3</digit>
</number>
<number>
<digit>6</digit>
</number>
<number>
<digit>1</digit>
</number>
<number>
<digit>2</digit>
</number>
<number>
<digit>7</digit>
</number>
<number>
<digit>4</digit>
</number>
</root>
Create a XSL stylesheet.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8"/>
<xsl:template match="/">
<html>
<head><title>Min - max sort</title>
</head>
<body>
<table width="20%" border="1">
<THEAD>
<TR>
<TD width="50%"><B>Max</B></TD>
<TD width="50%"><B>Min</B></TD>
</TR>
</THEAD>
<TBODY><TR>
<xsl:for-each select="root/number">
<xsl:sort select="digit" order="descending" data-type="number" />
<xsl:if test="position()=1"><TD><xsl:value-of select="."/></TD></xsl:if>
<xsl:if test="position()=last()"><TD><xsl:value-of select="."/></TD></xsl:if>
</xsl:for-each></TR>
</TBODY>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
<xsl:for-each select="root/number">
This finds all
<number> elements contained within the
<root> element.
<xsl:sort select="digit" order="descending" data-type="number" />
This sorts all
<digit> elements starting from the highest to the lowest.
<xsl:if test="position()=1"><TD><xsl:value-of select="."/></TD></xsl:if>
If the element found is the first (highest) value, will be displayed in a table cell.
<xsl:if test="position()=last()"><TD><xsl:value-of select="."/></TD></xsl:if>
If the element found is the last (lowest) value, it will be displayed in a table cell.
Related threads:
Trying to display selected data from xsl:sort
Back to
XML FAQ