[SOLVED] XSLT: Template to split strings based on a delimiter

Issue

I have been trying to come up with a template on transforming this:

<text>Smith, John / Smith, Dina / Smith, Susan</text>

into:

<rec>
    <RecNo>1</RecNo>
    <name>Smith, John</name>
</rec>
<rec>
    <RecNo>2</RecNo>
    <name>Smith, Dina</name>
</rec>
<rec>
    <RecNo>3</RecNo>
    <name>Smith, Susan</name>
</rec>

I am new to XSLT and I have been struggling to come up with a template to achieve the needed result. I have tried modifying the template here How to split strings, but I can’t achieve what I needed. Thanks in advance for the help.

Solution

Use this template:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="text()" name="split">
    <xsl:param name="pText" select="."/>
    <xsl:param name="index" select="1"/>
    <xsl:if test="string-length($pText)">
      <rec>
        <RecNo>
          <xsl:value-of select="$index"/>
        </RecNo>
        <name>
          <xsl:value-of select="substring-before(concat($pText,'/'),'/')"/>
        </name>
      </rec>
      <xsl:call-template name="split">
        <xsl:with-param name="pText" select="substring-after($pText, '/')"/>
        <xsl:with-param name="index" select="$index + 1"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Answered By – Kirill Polishchuk

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.