How do I generate a comma-separated list with XSLT/XPath?

xml, xpath, xslt

Solution

Take a look at the `position()`, `count()` and `last()` functions; e.g., `test="position() < last()"`.

Problem

Given this XML data: ``` <root> <item>apple</item> <item>orange</item> <item>banana</item> </root> ``` I can use this XSLT markup: ``` ... <xsl:for-each select="root/item"> <xsl:value-of select="."/>, </xsl:for-each> ... ``` to get this result: apple, orange, banana, but how do I produce a list where the last comma is not present? I assume it can be done doing something along the lines of: ``` ... <xsl:for-each select="root/item"> <xsl:value-of select="."/> <xsl:if test="...">,</xsl:if> </xsl:for-each> ... ``` but what should the test expression be? I need some way to figure out how long the list is and where I currently am in the list, or, alternatively, if I am currently processing the last element in the list (which means I don't care how long it is or what the current position is).

Original source