在xslt或whit中对变量中的值进行排序

时间:2014-01-20 10:09:03

标签: xslt xpath

如何在包含以逗号分隔的字符串的变量中对值进行排序?

如果变量在001a的子字符串上分开,那么就可以了。 我的变量是由逗号分隔的一串值,但因为我从更多文档连接字符串,所以它们的顺序不正确。它是这样的:

001a, 001b, 001d, 100a, 100c, 100d, 001c, 001f, 100b,... 

我想得到这个:

001a, 001b, 001c, 001d, 100a, 001b, 100c, 100d, 001f,...

1 个答案:

答案 0 :(得分:0)

使用XSL 2.0:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">
    <xsl:variable name="unsorted" select="'001a, 001b, 001d, 100a, 100c, 100d, 001c, 001f, 100b'"/>
    <xsl:variable name="sorted">
        <xsl:for-each select="tokenize($unsorted, ', ')">
            <xsl:sort select="." />
            <xsl:choose>
                <xsl:when test="position()!=last()">
                    <xsl:value-of select="."/><xsl:text>, </xsl:text>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>
    </xsl:variable>

    <xsl:template match="/">
        <unsorted><xsl:value-of select="$unsorted"/></unsorted>

        <sorted><xsl:value-of select="$sorted"/></sorted>
    </xsl:template>
</xsl:stylesheet>