stringxsltsplit

Does xslt have split() function?


How do you split a string based on some separator?

Given a string Topic1,Topic2,Topic3, I want to split the string based on , to generate:

Topic1 Topic2 Topic3

Solution

  • In XSLT 1.0 you have to built a recursive template. This stylesheet:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="text/text()" name="tokenize">
            <xsl:param name="text" select="."/>
            <xsl:param name="separator" select="','"/>
            <xsl:choose>
                <xsl:when test="not(contains($text, $separator))">
                    <item>
                        <xsl:value-of select="normalize-space($text)"/>
                    </item>
                </xsl:when>
                <xsl:otherwise>
                    <item>
                        <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
                    </item>
                    <xsl:call-template name="tokenize">
                        <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                    </xsl:call-template>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:template>
    </xsl:stylesheet>
    

    Input:

    <root>
    <text>Item1, Item2, Item3</text>
    </root>
    

    Output:

    <root>
        <text>
            <item>Item1</item>
            <item>Item2</item>
            <item>Item3</item>
        </text>
    </root>
    

    In XSLT 2.0 you have the tokenize() core function. So, this stylesheet:

    <xsl:stylesheet version="2.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="text/text()" name="tokenize">
            <xsl:param name="separator" select="','"/>
            <xsl:for-each select="tokenize(.,$separator)">
                    <item>
                        <xsl:value-of select="normalize-space(.)"/>
                    </item>
            </xsl:for-each>
        </xsl:template>
    </xsl:stylesheet>
    

    Result:

    <root>
        <text>
            <item>Item1</item>
            <item>Item2</item>
            <item>Item3</item>
        </text>
    </root>