Question

I am using XSLT version 1.0 and I have a requirement to split a text string delimited by pipes and use each of the value in xml elements. For example if the string is <Code>111|222|333|444</Code> then I want output as <Postalcode>111</Postalcode>

<Postalcode>222</Postalcode>
<Postalcode>333</Postalcode>
<Postalcode>444</Postalcode>

I have to do this using XSLT. Appreciate if anyone can help me on this.

Thanks, Ravi

Was it helpful?

Solution

Following stylesheet has a template named tokenize, which tokenizes string based on the separator passed and for every token creates Postalcode element:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="separator" />
    <xsl:choose>
        <xsl:when test="not(contains($text, $separator))">
            <Postalcode>
                <xsl:value-of select="$text"/>
            </Postalcode>
        </xsl:when>
        <xsl:otherwise>
            <Postalcode>
                <xsl:value-of select="normalize-space(substring-before($text, $separator))"/>
            </Postalcode>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $separator)"/>
                <xsl:with-param name="separator" select="$separator"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
<xsl:template match="/Code">
    <xsl:copy>
        <xsl:variable name="tokenize">
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="."/>
                <xsl:with-param name="separator" select="'|'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:copy-of select="$tokenize"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top