Search code examples
xsltxslt-1.0ibm-datapowerexslt

How to read 2 comma separated string in single loop - XSLT


I have below two variables which have multiple commas separated string values in different XSLT variable

Variable_01 : 88888,777777
Variable_02 : abc,xyz

Now I am looking for below output

[{"Group":"88888", "Name":"abc"},{"Group":"777777", "Name":"xyz"}]

Could you please help me what is correct XSLT code for the above output.


Solution

  • Here's one way you could look at it:

    XSLT 2.0

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="UTF-8"/>
    
    <xsl:variable name="Variable_01">88888,777777</xsl:variable>
    <xsl:variable name="Variable_02">abc,xyz</xsl:variable>
    
    <xsl:template match="/">
        <xsl:text>[</xsl:text>
        <xsl:for-each select="tokenize($Variable_01, ',')">
            <xsl:variable name="i" select="position()"/>
            <xsl:text>{"Group":"</xsl:text>
            <xsl:value-of select="." />
            <xsl:text>", "Name":"</xsl:text>
            <xsl:value-of select="tokenize($Variable_02, ',')[$i]" />
            <xsl:text>"}</xsl:text>
            <xsl:if test="position()!=last()">
                <xsl:text>,</xsl:text>
            </xsl:if>
        </xsl:for-each>
        <xsl:text>]</xsl:text>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    [{"Group":"88888", "Name":"abc"},{"Group":"777777", "Name":"xyz"}]
    

    Demo: http://xsltransform.hikmatu.com/jyH9rLV