2011-06-06 73 views
0

我希望能夠根據XML中的屬性對元素進行排序。不幸的是,我似乎無法得到它的工作,這是我的代碼到目前爲止。使用XSL動態排序順序

目前沒有錯誤產生,但排序似乎沒有應用降序。

 <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> 

回答

1
<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> 
    <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> 

輸出爲我:

<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> 
+0

我試過這個,但它不工作? – Chris 2011-06-06 11:04:52

+0

@Chris:它適合我。請顯示完整的代碼示例(儘可能小,但仍然失敗)。 – Tomalak 2011-06-06 11:06:52

+0

謝謝我用更多的信息更新了這個問題,並且使用了我正在使用的XML的一部分 – Chris 2011-06-06 11:13:33