Jatin Gadhiya
Jatin Gadhiya

Reputation: 2075

How to make array value with comma separated in XSLT 2.0

We have string array in XML look like:

<arr name="CategoryName">
   <str>Movies</str>
   <str>Movies</str>
   <str>Movies</str>
   <str>Movies</str>
   <str>Movies</str>
   <str>DVD</str>
   <str>By Languages</str>
   <str>By Title</str>
   <str>By Decades</str>
   <str>By Genre</str>
   <str>2000's</str>
   <str>Drama</str>
   <str>English</str>
   <str>QRST</str>
</arr>

and my output from xslt transformation look like:

<category>MoviesMoviesMoviesMoviesMoviesDVDBy LanguagesBy TitleBy DecadesBy Genre2000'sDramaEnglishQRST</category>

but i want to each element with comma separated like:

<category>Movies, Movies, Movies, Movies, Movies, DVD, By Languages, By Title, By Decades, By Genre, 2000's,Drama,English,QRST</category>

And my XSLT code look like:

<xsl:variable name="CategoryArray" select ="arr[@name = 'CategoryName']"/>

 <xsl:for-each select="$CategoryArray">
        <category><xsl:value-of select="concat($CategoryArray,', ')"/></category>
    </xsl:for-each>

but its not working so pls give me solution for how make array value with comma separated.

thanks in advance.

Upvotes: 0

Views: 1697

Answers (2)

Michael Kay
Michael Kay

Reputation: 163539

You can replace this:

<xsl:for-each select="$CategoryArray">
    <category><xsl:value-of select="concat($CategoryArray,', ')"/></category>
</xsl:for-each>

with this:

<category><xsl:value-of select="$CategoryArray" separator=", "/></category>

Upvotes: 2

vesan
vesan

Reputation: 3369

It's a little hard to tell what your code is doing without seeing how $CategoryArray is defined. However, there are 2 main problems with your code:

  1. The xsl:for-each needs to go inside the category element, because you only want one of these elements for every array
  2. Using your code, the list will end with a comma. To do this, you have to process the first item separately.

You can use this XSLT to do this:

<category>
  <xsl:if test="arr/str">
    <!-- Process the first item separately -->
    <xsl:value-of select="arr/str[1]"/>
    <!-- Process the rest of the items, skipping the first using position() -->
    <xsl:for-each select="arr/str[position() != 1]">
      <xsl:value-of select="concat(', ',.)"/>
    </xsl:for-each>
  </xsl:if>
</category>

Upvotes: 1

Related Questions