0

How can I order values in a variable that contains strings that are comma-separated?

It would be OK if the variable was separated on sub-strings of 001a and so on. My variable is a string of values separated by commas, but because I join strings from more documents they are not in the right order. It is something like this:

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

I would like to get this:

001a, 001b, 001c, 001d, 100a, 001b, 100c, 100d, 001f,...
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75

1 Answers1

0

Using 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>
Joel M. Lamsen
  • 7,143
  • 1
  • 12
  • 14