开发者

Dynamic sort order with XSL

开发者 https://www.devze.com 2023-03-10 11:54 出处:网络
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.

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

精彩评论

暂无评论...
验证码 换一张
取 消