Home : Tutorials : XML Tutorial


Displaying XML Files

Sorting the Results Using XSL File

In the Previous Example we have seen that Results are displayed Linearly one Book after another in the order they have been declared in the XML file. Now we want these Books to be Displayed Sorted by the Authors Name. Here's one of the Best Advantages that XML and XSL provide. Here when user wants to view data sorted by a different field, the we don't have to make a request again to the Database. The same XML file can be displayed sorted by a different field.

Here's the Syntax for Sorting the Data, Considering the same XML file which has the List of all Books declared in the previous page, now we  want to show the List of Books sorted by Authors Name,

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
  <html>
  <body>
    <table border="2" bgcolor="blue">
      <tr>
        <th>Title</th>
        <th>Author</th>
	<th>Publisher</th>
      </tr>
      <xsl:for-each select="LIBRARY/BOOK" order-by="+ AUTHOR">
      <tr>
        <td><xsl:value-of select="TITLE"/></td>
        <td><xsl:value-of select="AUTHOR"/></td>
	<td><xsl:value-of select="PUBLISHER"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Note that here we have added a new parameter called  order-by="+ AUTHOR". The "+" symbol indicates order in ascending order. For Descending order use "-" sign.  Here we asked the XSL file to sort the List of Books based on Authors name. So finally in the Output HTML files, all the Books will be shown in the Table Format, with Books sorted by Authors Name. 

If the Sort Parameter is a Number, then you can also you the <xsl:sort /> tag for specifying the sorting order. Here's the Syntax for using the Sort Tag.

.....
      <xsl:for-each select="LIBRARY/BOOK">
         <xsl:sort select="price"
                   data-type="number"
                   order="descending"/>

      <tr>
        <td><xsl:value-of select="TITLE"/></td>
        <td><xsl:value-of select="AUTHOR"/></td>
        <td><xsl:value-of select="PUBLISHER"/></td>
      </tr>
      </xsl:for-each>
......

In the above XSL file "xsl:sort" parameter acts a extra parameter to the "xsl:for-each" tag and helps in sorting the data.

Home  Previous Next


Home : Tutorials : XML Tutorial

 

Copyright© 1998-2004 All Rights Reserved. No portion of this site may be reproduced or redistributed without prior written permission from VistaEdge Technologies

All registered trademarks appearing on this site are the property of their respective owners. Java is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries. This site is not connected to Sun Microsystems, Inc. and is not sponsored by Sun Microsystems, Inc.