XSL for-each: how to detect last node?

Viewed 71014

I have this simple code:

<xsl:for-each select="GroupsServed">
  <xsl:value-of select="."/>,<br/>
</xsl:for-each></font>

I'm trying to add a comma for each item added.

This has 2 flaws:

  1. Case of when there's only 1 item: the code would unconditionally add a comma.
  2. Case of when there's more than 1 item: the last item would have a comma to it.

What do you think is the most elegant solution to solve this?

I'm using XSLT 2.0

4 Answers

Insert the column delimiter before each new item, except the first one. Then insert the line break outside the for-each loop.

<xsl:for-each select="GroupsServed">
  <xsl:if test="position() != 1">,</xsl:if>
  <xsl:value-of select="."/>
</xsl:for-each>
<br/>

In other words, treat every item like the last item. The exception is that the first item does not need a comma separator in front of it. The loop ends after the last item is processed, which also tells us where to put the break.

Related