How do I generate a comma-separated list with XSLT

2019-01-11 02:41发布

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).

标签: xml xslt xpath
7条回答
在下西门庆
2楼-- · 2019-01-11 03:48

This is a pretty common pattern:

<xsl:for-each select="*">
   <xsl:value-of select="."/>
   <xsl:if test="position() != last()">
      <xsl:text>,</xsl:text>
   </xsl:if>
</xsl:for-each>
查看更多
登录 后发表回答