xsl:sort (1)

  1. sort_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6.   <product id="p3" price="1200" stock="19"/>
  7.   <product id="p4" price="1500" stock="5"/>
  8.   <product id="p5" price="1225" stock="3"/>
  9. </products>
  1. sort_1-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="/">
  6.     <products>
  7.       <xsl:for-each select="products/product">
  8.         <xsl:sort select="@stock" data-type="number" order="descending"/>
  9.         <product id="{@id}" price="{@price}" stock="{@stock}"/>
  10.       </xsl:for-each>
  11.     </products>
  12.   </xsl:template>
  13. </xsl:stylesheet>
  1. sort_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <products>
  4.   <product id="p3" price="1200" stock="19"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6.   <product id="p4" price="1500" stock="5"/>
  7.   <product id="p1" price="3250" stock="4"/>
  8.   <product id="p5" price="1225" stock="3"/>
  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