Cover Image for XSLT xsl:sort
131 views

XSLT xsl:sort

In XSLT (Extensible Stylesheet Language Transformations), the xsl:sort element is used to sort nodes in the output of an XSLT transformation. It allows you to specify the sorting criteria based on one or more properties of the nodes, such as element values or attributes.

The xsl:sort element is typically used within a template that matches a parent element containing the nodes to be sorted. Here’s the basic syntax of the xsl:sort element:

<xsl:template match="parent-element">
  <xsl:apply-templates select="child-element">
    <xsl:sort select="sort-expression" order="ascending|descending" data-type="text|number|qname" />
  </xsl:apply-templates>
</xsl:template>

In this structure:

  • The xsl:sort element is nested within the xsl:apply-templates or xsl:for-each element that processes the child nodes of the parent element.
  • The select attribute of xsl:sort specifies an XPath expression that evaluates to the value used for sorting. It can be an element value, an attribute value, or any other expression that produces a value.
  • The order attribute is optional and can have the values “ascending” (default) or “descending” to determine the sorting order.
  • The data-type attribute is optional and can have the values “text” (default), “number,” or “qname” to specify the data type of the sort key. It affects how the sorting is performed.

Here’s an example of using xsl:sort to sort a list of books by their titles in ascending order:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <sorted-books>
      <xsl:apply-templates select="books/book">
        <xsl:sort select="title" order="ascending" />
      </xsl:apply-templates>
    </sorted-books>
  </xsl:template>

  <xsl:template match="book">
    <sorted-book>
      <xsl:value-of select="title" />
    </sorted-book>
  </xsl:template>
</xsl:stylesheet>

In this example, assuming the XML input contains a list of <book> elements with a child element <title>, the XSLT transformation will produce a new XML output with the <book> elements sorted alphabetically by their titles.

xsl:sort is a useful element in XSLT for organizing and presenting data in a specific order. By specifying sorting criteria, you can control how the output is arranged, making it easier to generate structured and organized output from XML data.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS