xsl:perform-sort

  1. perform-sort_1-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. perform-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.     <xsl:variable name="product">
  7.       <xsl:perform-sort select="products/product">
  8.         <xsl:sort select="@stock" data-type="number" order="descending"/>
  9.         <xsl:sort select="@country" order="ascending"/>
  10.       </xsl:perform-sort>
  11.     </xsl:variable>
  12.     <products>
  13.       <xsl:copy-of select="$product"/>
  14.     </products>
  15.   </xsl:template>
  16. </xsl:stylesheet>
  1. perform-sort_1-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

In XSLT 2.0 xsl:perform-sort can be used to sort the content of e.g. a variable without using xsl:for-each or xsl:apply-templates.

Updated 2009-03-19