Sorting Elements

You can use the <xsl: sort > element to sort node sets. You use this element inside <xsl:apply-templates> and then use its select attribute to specify what to sort on. For example, here's how I sort the planets based on density:

Listing ch13_24.xsl
 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">     <xsl:template match="PLANETS">         <HTML>             <HEAD>                 <TITLE>                     Planets                 </TITLE>             </HEAD>             <BODY>                 <H1>Planets sorted by density</H1>                 <TABLE BORDER="1">                     <TD>Planet</TD>                     <TD>Mass</TD>                     <TD>Day</TD>                     <TD>Density</TD>  <xsl:apply-templates>   <xsl:sort select="DENSITY"/>   </xsl:apply-templates>  </TABLE>             </BODY>         </HTML>     </xsl:template>     <xsl:template match="PLANET">         <TR>             <TD><xsl:apply-templates select="NAME"/></TD>             <TD><xsl:apply-templates select="MASS"/></TD>             <TD><xsl:apply-templates select="DAY"/></TD>             <TD><xsl:apply-templates select="DENSITY"/></TD>         </TR>     </xsl:template> </xsl:stylesheet> 

Here are the results of this transformation:

 <HTML>  <HEAD> <TITLE>                     Planets                 </TITLE> </HEAD> <BODY> <H1>Planets sorted by density</H1> <TABLE BORDER="1"> <TD>Planet</TD><TD>Mass</TD><TD>Day</TD><TD>Density</TD> <TR> <TD>Venus</TD><TD>.815</TD><TD>116.75</TD><TD>.943</TD> </TR> <TR> <TD>Mercury</TD><TD>.0553</TD><TD>58.65</TD><TD>.983</TD> </TR> <TR> <TD>Earth</TD><TD>1</TD><TD>1</TD><TD>1</TD> </TR> </TABLE> </BODY> </HTML> 

You can see this HTML page in Figure 13-4.

Figure 13-4. Sorting planets by density.

graphics/13fig04.gif

Note that, by default, <xsl:sort> performs a an alphabetic sort, which means that 10 will come before 2 . You can perform a true numeric sort by setting the data-type attribute to "number" , like this:

 <xsl:sort data-type="number" select="DENSITY"/> 

Descending Sorts

You can also create descending sorts by setting the <xsl:sort> element's order attribute to "descending" .



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net