How to Concatenate (Join) Values from Several Rows in XSLT

Situation

Given you have the following XML as a source:

<Rows>
    <Row Username="user1"/>
    <Row Username="user2"/>
    <Row Username="user3"/>
</Rows>

You’re asked to provide the following output:

<Users>user1, user2, user3</Users>

Solution

Using xsl:for-each in an XSLT transformation provides the needed functionality:

<xsl:template match="Rows">
    <Users>
         <xsl:for-each select="Row">
             <xsl:choose>
                 <xsl:when test="position() = 1">
                     <xsl:value-of select="@Username"/>
                 </xsl:when>
                 <xsl:otherwise>
                     <xsl:value-of select="', '"/>
                     <xsl:value-of select="@Username"/>
                 </xsl:otherwise>
             </xsl:choose>
         </xsl:for-each>
    </Users>
</xsl:template>
1 Like

There is a slite mistake in a XSLT transformation according to given XML source. The for-reach should be

<xsl:for-each select="Row">

Fixed. Thanks a lot.