Important:
This is retired content. This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This content may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
A version of this page is also available for
4/8/2010

The last Functioncan be used to determine if the element is the last one in the query.

Copy Code
<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.

Copy Code
<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> orderattribute 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.

Copy Code
<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.

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

See Also

Reference

last Function

Concepts

XPath