Split a String

Last change 25/04/2014

It happened already quite often, that I had to "misuse" a field ina xml-based cms solution. For example I created a comma seperated list in order to have all information available in xsl. This snippet shows you how to take such a list and play with it as if it were a subtree - in xslt 1.0.

The template

This template simply takes a string with seperators and creates <token>Stringpart</token> subtree out of it.

    <!--
        split a string into tokens using a seperator
    -->
    <xsl:template name="tokenizeString">
        <xsl:param name="string"/>
        <xsl:param name="separator"/>

        <xsl:if test="string-length($string) > 0">
            <xsl:variable name="before-separator" select="substring-before($string, $separator)"/>
            <xsl:variable name="after-separator" select="substring-after($string, $separator)"/>

            <xsl:choose>
                <!-- separator not found in string -->
                <xsl:when test="string-length($before-separator)=0 and string-length($after-separator)=0">
                    <token>
                        <xsl:value-of select="$string"/>
                    </token>
                </xsl:when>
                <xsl:otherwise>
                    <token>
                        <xsl:value-of select="$before-separator"/>
                    </token>
                    <xsl:call-template name="tokenizeString">
                        <xsl:with-param name="string" select="$after-separator"/>
                        <xsl:with-param name="separator" select="$separator"/>
                    </xsl:call-template>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:if>
    </xsl:template>

Usage

In order to use this kind of subtree you need to use a xslt extension

 

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl" exclude-result-prefixes="exsl" version="1.0">

 


Then you need two variables to save the tokens in. In this example we take a string saved in the node "description" in the format "value|value|value" and generate one li for each
<xsl:variable name="sTmp">
    <xsl:call-template name="tokenizeString">
        <xsl:with-param name="separator" select="'|'"/>
        <xsl:with-param name="string" select="description"/>
    </xsl:call-template>
</xsl:variable>
<xsl:variable name="s" select="exsl:node-set($sTmp)"/>
<ul>
<xsl:for-each select="$sTmp">
    <li><xsl:value-of select="."/></li>
</xsl:for-each>
</ul>

Site created with Corinis CCM