3

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.

Community
  • 1
  • 1
Elmer Calonzo
  • 33
  • 1
  • 5

2 Answers2

1

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>
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
0

We can Tokenize the values based on symbol.

<xsl:variable name="tokenizedList" select="tokenize("Smith, John / Smith, Dina / Smith, Susan", ' / ')" />

Pass values to for-each to fetch each values in a node.

<xsl:for-each select="$tokenizedList">
<rec>
    <RecNo><xsl:value-of select="position()"/></RecNo>
    <name><xsl:value-of select="."/></name>
</rec>
</xsl:for-each>

Hope this helpful for others.

Navaneeth
  • 51
  • 4
  • 1
    This question is about XSLT 1.0. Your answer requires XSLT 2.0. – michael.hor257k Jul 19 '22 at 09:30
  • He didn't mention about xslt version. i added this comment for others as well. if someone wants to do it in easy way in xslt 2.0. they can use this approach. it is 6 years old post, already he got answer for his question. – Navaneeth Jul 21 '22 at 08:04
  • OP tagged this question as `xslt-1.0`. If you want to post an XSLT 2.0 answer, the least you could is warn others about it. – michael.hor257k Jul 21 '22 at 09:46