Microsoft XML SDK 2.6 - XSLT Developer's Guide

Creating a Comma-Separated List of Items

The last() function can be used to determine whether the element is the last one in the query.

<DIV>
  <xsl:for-each select="products/product">
    <xsl:value-of select="."/> <xsl:if test="position()!=last()">, </xsl:if> 
    </xsl:for-each>
</DIV>

Because the comma is being inserted based on the position in the query and not based on the position in the source document, the list can be sorted without creating errors in the results. The following template shows how to add commas to a sorted product list.

<DIV>
  <xsl:for-each select="products/product">
    <xsl:sort select="product" order="descending"/>
      <xsl:value-of select="."/><xsl:if test="position()!=last()">, </xsl:if> 
  </xsl:for-each>
</DIV>

The <xsl:sort> order attribute is given the value "descending" to indicate a descending sort by product name.

In the following example, the names in a group of names are formatted as a comma-separated list:

<xsl:template match="namelist/name">
  <xsl:apply-templates/>
  <xsl:if test="position()!=last()">, </xsl:if>
</xsl:template>

Another way to accomplish this is by reversing the logic to verify whether this name is the first. In some circumstances this performs better than the above example because last() requires that the entire set of names be found and counted, while this one does not.

<xsl:template match="namelist/name">
  <xsl:if test="position()!=1">, </xsl:if>
  <xsl:apply-templates/>
</xsl:template>

Try it!   View the result of the above templates in the Product List (Commas) Sample found at XSLT Developer's Guide Samples.

See the XSL version of this sample at XSL Developer's Guide Samples.