Monday, 12 March 2012

Split string in XSLT 1.0

Consider the following XML:


<?xml version="1.0" encoding="utf-8"?>
<RootElement>
    <Text>First, Second, Third, Fourth</Text>
</RootElement>


If you want to split the string value of the <Text> tag and put the split values in separate tags using XSLT 1.0, use the following code:



<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match ="/">
    <xsl:element name="SplitXML">
         <xsl:call-template name="tmpSplitString">

             <xsl:with-param name="stringtosplit" select ="RootElement /Text" />
        </xsl:call-template>
    </xsl:element>
  </xsl:template>


  <xsl:template name="tmpSplitString">
    <xsl:param name="stringtosplit" />
    <xsl:variable name="first" select="substring-before($stringtosplit, ',')" />
    <xsl:variable name="remaining" select="substring-after($stringtosplit, ',')" />
    <xsl:element name ="Split">
      <xsl:value-of select="$first" />
    </xsl:element>
    <xsl:if test="$remaining">
      <xsl:call-template name="tmpSplitString">
        <xsl:with-param name="stringtosplit" select="$remaining" />
      </xsl:call-template>
    </xsl:if>
  </xsl:template>


</xsl:stylesheet>


The above XSLT uses recursive call to the template to split the string using , (comma) as delimiter.

The output XML will look like:

<SplitXML>
   <Split>First</Split>
   <Split>Second</Split>
   <Split>Third</Split>
   <Split>Fourth</Split>
</SplitXML>