René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

XSL: sorting

See also this example.
The XML File:
<?xml version="1.0" ?>

<famous-persons>

<persons category="medicine">
  <person>
    <firstname> Edward   </firstname>
    <name>      Jenner   </name>
  </person>

  <person>
    <firstname> Gertrude </firstname>
    <name>      Elion    </name>
  </person>
</persons>

<persons category="computer science">
  <person>
    <firstname> Charles  </firstname>
    <name>      Babbage  </name>
  </person>

  <person>
    <firstname> Alan     </firstname>
    <name>      Touring  </name>
  </person>

  <person>
    <firstname> Ada      </firstname>
    <name>      Byron    </name>
  </person>
</persons>

<persons category="astronomy">
  <person>
    <firstname> Tycho    </firstname>
    <name>      Brahe    </name>
  </person>

  <person>
    <firstname> Johannes </firstname>
    <name>      Kepler   </name>
  </person>

  <person>
    <firstname> Galileo  </firstname>
    <name>      Galilei  </name>
  </person>
</persons>

</famous-persons>
The XSL File:
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">
     <html><head><title>Sorting example</title></head><body>

     <xsl:apply-templates select="famous-persons/persons">
       <xsl:sort select="@category" />
     </xsl:apply-templates>

     </body></html>
  </xsl:template>

  <xsl:template match="persons">

    <h2><xsl:value-of select="@category" /></h2>
    <ul>

       <xsl:apply-templates select="person">
         <xsl:sort select="name"      />
         <xsl:sort select="firstname" />
       </xsl:apply-templates>

    </ul>

  </xsl:template>

  <xsl:template match="person">

        <xsl:text disable-output-escaping="yes">
            &lt;li&gt;
        </xsl:text>

        <b><xsl:value-of select="name"      /></b>
           <xsl:value-of select="firstname" />

  </xsl:template>

</xsl:stylesheet>
The Output (whitespaces manually modified):
<html><head>    
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sorting example</title></head>
<body>

  <h2>astronomy</h2>
    <ul>
            <li> <b>Brahe    </b> Tycho    
            <li> <b>Galilei  </b> Galileo  
            <li> <b>Kepler   </b> Johannes 
    </ul>

  <h2>computer science</h2>
    <ul>
            <li> <b>Babbage  </b> Charles  
            <li> <b>Byron    </b> Ada      
            <li> <b>Touring  </b> Alan     
    </ul>

  <h2>medicine</h2>
    <ul>
            <li> <b>Elion    </b> Gertrude 
            <li> <b>Jenner   </b> Edward   
    </ul>

  </body></html>