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)"/>

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


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:variable name="s" select="exsl:node-set($sTmp)"/>
<xsl:for-each select="$sTmp">
    <li><xsl:value-of select="."/></li>

Site created with Corinis CCM