Dynamic sort order with XSL
I want to be able to sort elements based on an attribute in my XML. Unfortunately I cannot seem to get it to work, here is my code so far.
Currently no errors are produced but the sort doesn't seem开发者_JAVA百科 to ever be applied descending.
<xsl:variable name="sortOrder">
<xsl:choose>
<xsl:when test="Lanes/@flip = 1">descending</xsl:when>
<xsl:otherwise>ascending</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:for-each select="Entry">
<xsl:sort data-type="number" select="@id" order="{$sortOrder}"/>
</xsl:for-each>
XML:
<Lanes flip="1">
<Entry id="1" value="0"/>
<Entry id="2" value="0"/>
</Lanes>
<xsl:for-each select="Entry">
<xsl:sort data-type="number" select="@id" order="{$sortOrder}"/>
</xsl:for-each>
Test case for your sample:
<xml>
<Lanes flip="1">
<Entry id="1" value="0"/>
<Entry id="2" value="0"/>
</Lanes>
<Lanes flip="0">
<Entry id="1" value="0"/>
<Entry id="2" value="0"/>
</Lanes>
</xml>
XSL
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:output indent="yes" />
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Lanes">
<xsl:copy>
<xsl:variable name="sortOrder">
<xsl:choose>
<xsl:when test="@flip = 1">descending</xsl:when>
<xsl:otherwise>ascending</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:apply-templates select="Entry">
<xsl:sort data-type="number" select="@id" order="{$sortOrder}" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Output for me:
<xml>
<Lanes>
<Entry id="2" value="0"></Entry>
<Entry id="1" value="0"></Entry>
</Lanes>
<Lanes>
<Entry id="1" value="0"></Entry>
<Entry id="2" value="0"></Entry>
</Lanes>
</xml>
精彩评论