This is the mail archive of the
xsl-list@mulberrytech.com
mailing list .
Dynamic Sorting - Using a variable to determine the sort select expression
- To: "'XSL-List at lists dot mulberrytech dot com'" <XSL-List at lists dot mulberrytech dot com>
- Subject: [xsl] Dynamic Sorting - Using a variable to determine the sort select expression
- From: Mark Swardstrom <mark at nimble dot com>
- Date: Mon, 2 Apr 2001 10:58:50 -0700
- Reply-To: xsl-list at lists dot mulberrytech dot com
Hi - I'm trying to dynamically sort a list based on the value of an element
in my xml document. Ideally, I'd be able to pass this value to the xsl:sort
element in the xsl document to determine the sort criteria. In the example
below, "sortby" could have the value "name" or "age".
Here's the XML:
<root>
<sortby>name</sortby>
<data>
<person><name>Bob</name><age>21</age></person>
<person><name>Jim</name><age>63</age></person>
<person><name>Gus</name><age>55</age></person>
<person><name>Van</name><age>18</age></person>
<person><name>Sam</name><age>32</age></person>
<person><name>Don</name><age>39</age></person>
<person><name>Ron</name><age>33</age></person>
</data>
</root>
And here's the XSL I tried (it doesn't work, but you'll see what I'm trying
to do). I also tried curly braces in the xsl:sort select tag to evaluate
the sortexpression string as an expression, but no luck. I understand
that's not the intended use of the curly brackets, but gave it a shot.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="no"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="root">
<xsl:apply-templates select="data">
<xsl:with-param name="sortexpression" select="sortby"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="data">
<xsl:param name="sortexpression"/>
<xsl:apply-templates select="person">
<xsl:sort select="$sortexpression"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="person">
<xsl:value-of select="name"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="age"/>
<br />
</xsl:template>
</xsl:stylesheet>
If I can't do this, I find I have to write a bunch of xsl:if clauses and
that solution doesn't scale and results in bulky code.
Thanks ahead of time for your thoughts.
Mark Swardstrom
Nimble Technology
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list