XSL for-each: how to detect last node?

2019-01-17 09:45发布

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

标签: xslt
3条回答
放荡不羁爱自由
2楼-- · 2019-01-17 09:51

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()" />
查看更多
Rolldiameter
3楼-- · 2019-01-17 09:57

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>
查看更多
做个烂人
4楼-- · 2019-01-17 10:09
<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>
查看更多
登录 后发表回答