XSL for-each: how to detect last node?
Asked Answered
M

4

61

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

Muslin answered 15/11, 2009 at 21:5 Comment(2)
This question may be of use #798769Garnes
right, but I actually I want to include a new line for each item as well.Muslin
G
96

If you're using XSLT 2.0, the canonical answer to your problem is

<xsl:value-of select="GroupsServed" separator=", " />

On XSLT 1.0, the somewhat CPU-expensive approach to finding the last element in a node-set is

<xsl:if test="position() = last()" />
Goltz answered 15/11, 2009 at 21:11 Comment(2)
I shouldn't try to answer these questions via a phone. I've added the detail on the XSLT2.0 method, in case it wasn't clear earlier.Goltz
Couldn't get this syntax to work, if by any chance you could help on this one... #62006412Dead
M
32

Final answer:

<xsl:for-each select="GroupsServed">
  <xsl:value-of select="."/>                                    
  <xsl:choose>
    <xsl:when test="position() != last()">,<br/></xsl:when>
  </xsl:choose>
</xsl:for-each>
Muslin answered 15/11, 2009 at 21:31 Comment(0)
R
4
<xsl:variable name="GROUPS_SERVED_COUNT" select="count(GroupsServed)"/>
<xsl:for-each select="GroupsServed">
    <xsl:value-of select="."/>
    <xsl:if test="position() < $GROUPS_SERVED_COUNT">
        ,<br/>
    </xsl:if>
</xsl:for-each></font>
Rodenhouse answered 29/3, 2017 at 12:48 Comment(0)
W
3

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.

Whaler answered 7/1, 2022 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.