Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT split string on every character

Tags:

xslt

I have a string like : "ABCDEFGHI" I want the output as A,B,C,D,E,F,G,H,I in xslt-

I have been using -

<xsl:variable name="string_Comma_Delimited">a,b,c,d,e,f,g,h,i</xsl:variable>

<xsl:call-template name="parseString">
  <xsl:with-param name="list" select="$string_Comma_Delimited"/>
 </xsl:call-template>


<xsl:template name="parseString">
<xsl:param name="list"/>

<xsl:if test="contains($list, ',')">
     <fo:table-cell border-width="0.000pt " border-style="solid" border-color="rgb(0,0,0)" padding-top="4.000pt">
        <fo:block-container  height="6mm" border-width="0.200pt" border-style="solid" border-color="rgb(0,0,0)" text-align="center">
        <fo:block text-align="center">
                <xsl:value-of select="substring-before($list, ',')"/>
        </fo:block>
        </fo:block-container>
    </fo:table-cell>
 <xsl:call-template name="parseString">
  <xsl:with-param name="list" select="substring-after($list, ',')"/>
 </xsl:call-template>
</xsl:if>

</xsl:template>
like image 811
gyanendra Avatar asked Sep 02 '25 17:09

gyanendra


1 Answers

Your current template splits the string by commas. To simply split it on every single character you can still use a recursive template. All the template would do is output the first character using substring, and then, if the length of the string was 2 or more characters, recursively call the template with the remaining portion of the string.

Try this

<xsl:template name="parseString">
    <xsl:param name="text"/>
    <letter>
        <xsl:value-of select="substring($text, 1, 1)"/>
    </letter>
    <xsl:if test="string-length($text) > 1">
        <xsl:call-template name="parseString">
            <xsl:with-param name="text" select="substring($text, 2, string-length($text) - 1)"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

Given INDIA as input, the following is output:

<letter>I</letter>
<letter>N</letter>
<letter>D</letter>
<letter>I</letter>
<letter>A</letter>

Now, if you were using XSLT 2.0, you could use the xsl:analyze-string function to achieve the same

<xsl:template name="parseString">
    <xsl:param name="text"/>
    <xsl:analyze-string select="$text" regex=".">
        <xsl:matching-substring>
            <letter>
                <xsl:value-of select="." />
            </letter>
        </xsl:matching-substring>
    </xsl:analyze-string>
</xsl:template>

(Of course, if you were using XSLT 2.0, you could have used tokenize in the first case to split the comma-delimited string)

like image 98
Tim C Avatar answered Sep 05 '25 09:09

Tim C