Wednesday, May 23, 2012

XSLT Loop Over a Comma Delimited String

Context:

XSLT 1.0
XPath 1.0

Problem:

I needed to loop over a comma delimited string to work individually with each value in the string.

Solution:

Here's the sample string:  1,2,3,4,        

<xsl:call-template name="SimpleStringLoop">
    <xsl:with-param name="input" select="'1,2,3,4,'"/>
</xsl:call-template>

<xsl:template name="SimpleStringLoop">
    <xsl:param name="input"/>
    <xsl:if test="string-length($input) &gt; 0">
      <xsl:variable name="v" select="substring-before($input, ',')"/>
      <xsl:value-of select="$v"/>
      <xsl:call-template name="SimpleStringLoop">
        <xsl:with-param name="input" select="substring-after($input, ',')"/>
      </xsl:call-template>
    </xsl:if> 

</xsl:template>

3 comments: