xsl:sort (2 )

  1. sort_2-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4" country="Denmark"/>
  5.   <product id="p2" price="1000" stock="5" country="Germany"/>
  6.   <product id="p3" price="1200" stock="19" country="Germany"/>
  7.   <product id="p4" price="1500" stock="5" country="Australia"/>
  8.   <product id="p5" price="1225" stock="3" country="Japan"/>
  9. </products>
  1. sort_2-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="products">
  6.     <products>
  7.       <xsl:apply-templates select="product">
  8.         <xsl:sort select="@stock" data-type="number" order="descending"/>
  9.         <xsl:sort select="@country" order="ascending"/>
  10.       </xsl:apply-templates>
  11.     </products>
  12.   </xsl:template>
  13.   <xsl:template match="product">
  14.     <product id="{@id}" price="{@price}" stock="{@stock}" country="{@country}"/>
  15.   </xsl:template>
  16. </xsl:stylesheet>
  1. sort_2-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <products>
  4.   <product id="p3" price="1200" stock="19" country="Germany"/>
  5.   <product id="p4" price="1500" stock="5" country="Australia"/>
  6.   <product id="p2" price="1000" stock="5" country="Germany"/>
  7.   <product id="p1" price="3250" stock="4" country="Denmark"/>
  8.   <product id="p5" price="1225" stock="3" country="Japan"/>
  9. </products>

Comment

xsl:sort can be used inside xsl:for-each, xsl:for-each-group, xsl:apply-templates and inside xsl:perform-sort (XSLT 2.0). All attributes in xsl:sort are optional. Some of the more important are used in example.

Updated 2009-03-19