Creating a Comma-Separated List of Items
A version of this page is also available for
4/8/2010
The last Function can be used to determine if 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 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 cases, this performs better than the preceding 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>