Re: [xsl] Dynamically define number of xsl:sort stmts using parameters

Subject: Re: [xsl] Dynamically define number of xsl:sort stmts using parameters
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Wed, 28 Mar 2007 17:36:16 +0100
On 3/28/07, Angela Williams <Angela.Williams@xxxxxxxxxxxxxxxxxx> wrote:

My esteemed colleague came up with a better idea - gosh, I hate it when
I forget the power of xpath!

<?xml version="1.0" encoding="UTF-8"?>
  <employee hireDate="04/23/1999">

  <employee hireDate="09/01/1998">

  <employee hireDate="08/20/2000">

  <sort order="1">last</sort>
  <sort order="2">first</sort>

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="";
version="2.0" xmlns:saxon="";>

<xsl:output method="text" />

  <xsl:template match="employees">
    <xsl:variable name="sort1" select="sort[@order='1']" />
    <xsl:variable name="sort2" select="sort[@order='2']" />
    <xsl:variable name="sort3" select="sort[@order='3']" />
    <xsl:variable name="sort4" select="sort[@order='4']" />

    <xsl:for-each select="employee">
          select="if ($sort1) then saxon:evaluate($sort1) else 'foo'" />
          select="if ($sort2) then saxon:evaluate($sort2) else 'foo'" />
          select="if ($sort3) then saxon:evaluate($sort3) else 'foo'" />
          select="if ($sort4) then saxon:evaluate($sort4) else 'foo'" />

Last: <xsl:apply-templates select="last" /> First: <xsl:apply-templates select="first" /> Salary: <xsl:apply-templates select="salary" /> Hire Date: <xsl:apply-templates select="@hireDate" /> <xsl:text> </xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>

Here's a way of sorting dynamically without extensions:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"

<xsl:variable name="employees" select="/employees/employee"/>
<xsl:variable name="sortValues" select="/employees/sort" as="xs:string+"/>

<xsl:function name="fn:performSort" as="element()+">
	<xsl:param name="list" as="element()+"/>
	<xsl:param name="sortKey" as="xs:string+"/>
	<xsl:variable name="sortedList" as="element()+">
		<xsl:for-each select="$list">
			<xsl:sort select="*[name() = $sortKey[1]]"/>
			<xsl:copy-of select="."/>
	<xsl:sequence select="if ($sortKey[2]) then
							fn:performSort($sortedList, subsequence($sortKey, 2))
							else $sortedList"/>

<xsl:template match="/">
	<xsl:sequence select="fn:performSort($employees, $sortValues)"/>


You call the performSort() function with a list of elements to sort,
and a list of child element names to sort with, and it recursively
sorts by each one.

hope this helps,


Current Thread