xml
  1. xml-xsl-sort

XML xsl:sort

  • The xsl:sort is one of the fundamental elements of XSLT, which is used for sorting the nodes generated by an XSLT transform.
  • It is used to control the order in which the nodes should appear in the output.

Syntax

The syntax for xsl:sort is as follows:

<xsl:sort select="xpath-expression" order="sorting-order" data-type="data-type"/>
  • xpath-expression: It specifies the XPath expression that is used to select the nodes that needs to be sorted.
  • sorting-order: It defines the sorting order which can be "ascending" or "descending".
  • data-type: It is used to specify the data type of the nodes being sorted. It should be one of the following values - text, number, datetime, or date.

Example

Let's consider an example where we want to sort a list of employees based on their salary in ascending order:

<xsl:template match="/">
   <employees>
      <xsl:for-each select="employees/employee">
         <xsl:sort select="salary" order="ascending" data-type="number"/>
         <employee>
            <name><xsl:value-of select="name"/></name>
            <salary><xsl:value-of select="salary"/></salary>
         </employee>
      </xsl:for-each>
   </employees>
</xsl:template>

Output

The output generated by the above example would be as follows:

<employees>
   <employee>
      <name>Alice</name>
      <salary>5000</salary>
   </employee>
   <employee>
      <name>Bob</name>
      <salary>10000</salary>
   </employee>
   <employee>
      <name>Charlie</name>
      <salary>15000</salary>
   </employee>
</employees>

Explanation

In the above example, we have selected all the employee nodes using the XPath expression employees/employee. Then, we have used xsl:sort to sort the selected nodes based on the salary element in ascending order. Finally, we have created the employee element with the sorted nodes and added the name and salary elements with their respective values using xsl:value-of elements.

Use

The xsl:sort is used to sort nodes in an XSLT transform. It can be used in combination with xsl:for-each or xsl:apply-templates elements to handle a set of nodes and generate a sorted output.

Important Points

  • If the order attribute is not specified, the default value is "ascending".
  • If the data-type attribute is not specified, the default value is "text".
  • It can be used with any node set, but it is particularly useful when working with xsl:for-each and xsl:apply-templates elements.
  • The xsl:sort element should always be a child of xsl:for-each or xsl:apply-templates.

Summary

The xsl:sort is a core element of XSLT that is used to sort the nodes generated by an XSLT transform. It takes an XPath expression as input and sorts the selected nodes based on the criteria specified in the order and data-type attributes. It is mainly used with the xsl:for-each and xsl:apply-templates elements to generate a sorted output.

Published on: