ncyoung.com

using a variable or parameter as sort order criteria in XSL

This entry is in the following categories:

I had a lot of frustration trying to use a global parameter (passed into the stylesheet from Perl) to determine the sort order in an xsl:sort element.

Example: Applying templates to output books sorted by author might look like this:

<xsl:apply-templates select="Book">
<xsl:sort select="Author"/>
</xsl:apply-templates>

If you want to pass in a parameter (or use a variable for that matter) so that you could choose weather to sort by author, title, or date, you might think you could use the variable $orderBy in the sort like so:

<xsl:apply-templates>
<xsl:sort select="$orderBy"/>
</xsl:apply-templates>

You can't!!

You can however, work around it like this:

<xsl:apply-templates>
<xsl:sort select="*[name()=$orderBy]"/>
</xsl:apply-templates>

I kind of understand why, but not well enough to explain. I'll try to update this post later on.



Dated: 09/26/2003