Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

xslt - XSL for-each: how to detect last node?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...