MadMax1138
MadMax1138

Reputation: 286

How do I render a comma delimited list using xsl:for-each

I am rendering a list of tickers to html via xslt and I would like for the list to be comma deliimited. Assuming I was going to use xsl:for-each...

<xsl:for-each select="/Tickers/Ticker">
    <xsl:value-of select="TickerSymbol"/>,
</xsl:for-each>

What is the best way to get rid of the trailing comma? Is there something better than xsl:for-each?

Upvotes: 6

Views: 5884

Answers (4)

Kevin Kussmaul
Kevin Kussmaul

Reputation: 280

I know you said xsl 2.0 is not an option and it has been a long time since the question was asked, but for all those searching for a posibility to do what you wanted to achieve:

There is an easier way in xsl 2.0 or higher

<xsl:value-of separator=", " select="/Tickers/Ticker/TickerSymbol" />

This will read your /Tickers/Ticker elements and insert ', ' as separator where needed

If there is an easier way to do this I am looking forward for advice

Regards Kevin

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422076

<xsl:for-each select="/Tickers/Ticker">
    <xsl:if test="position() > 1">, </xsl:if>
    <xsl:value-of select="TickerSymbol"/>
</xsl:for-each>

Upvotes: 18

Tim C
Tim C

Reputation: 70628

In XSLT 1.0, another alternative to using xsl:for-each would be to use xsl:apply-templates

<xsl:template match="/">

   <!-- Output first element without a preceding comma -->
   <xsl:apply-templates select="/Tickers/Ticker[position()=1]" />

   <!-- Output subsequent elements with a preceding comma -->
   <xsl:apply-templates select="/Tickers/Ticker[position()&gt;1]">
      <xsl:with-param name="separator">,</xsl:with-param>
   </xsl:apply-templates>

</xsl:template>

<xsl:template match="Ticker">
   <xsl:param name="separator" />
   <xsl:value-of select="$separator" /><xsl:value-of select="TickerSymbol" />
</xsl:template>

Upvotes: 2

Mads Hansen
Mads Hansen

Reputation: 66723

In XSLT 2.0 you could do it (without a for-each) using the string-join function:

<xsl:value-of  select="string-join(/Tickers/Ticker, ',')"/>  

Upvotes: 7

Related Questions