xslt - Remove comma from last element
I have the following XSLT macro (in Umbraco)
<xsl:param name="currentPage"/>
<xsl:template match="/">
<xsl:apply-templates select="$currentPage/imageList/multi-url-picker" />
</xsl:template>
<xsl:template match="url-picker">
<xsl:variable name="url"><xsl:value-of select="./url" /></xsl:variable>
<xsl:value-of select="concat('"', $url, '",')" />
</xsl:template>
I would like to not add the comma to the last url-picker in the collection. How would I go about doing this?
Edit: The XML schema, just for reference:
<multi-url-picker>
<url-picker mode="URL">
<new-window>True</new-window>
<node-id />
<url>http://our.umbraco.org</url>
&l开发者_C百科t;link-title />
</url-picker>
<url-picker mode="Content">
<new-window>False</new-window>
<node-id>1047</node-id>
<url>/homeorawaytest2.aspx</url>
<link-title />
</url-picker>
<url-picker mode="Media">
<new-window>False</new-window>
<node-id>1082</node-id>
<url>/media/179/bolero.mid</url>
<link-title>Listen to this!</link-title>
</url-picker>
<url-picker mode="Upload">
<new-window>False</new-window>
<node-id />
<url>/media/273/slide_temp.jpg</url>
<link-title />
</url-picker>
Use:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="url">
<xsl:if test="not(position()=1)">
<xsl:text>,</xsl:text>
</xsl:if>
<xsl:value-of select="concat('"', ., '"')" />
</xsl:template>
</xsl:stylesheet>
when applied on this XML document (none was provided!):
<url-picker>
<url>1</url>
<url>2</url>
<url>3</url>
</url-picker>
the wanted, correct result is produced:
"1","2","3"
Do note:
You don't need the variable
$url
.If you need such variable, never create a child node (this results in an RTF). always use the
select
attribute ofxsl:variable
:
Instead of:
<xsl:variable name="url"><xsl:value-of select="./url" /></xsl:variable>
write:
<xsl:variable name="url" select="url" />
.3. It is a good practice to use some naming convention for variables, so that if the $
is skipped accidentally, the name will not easily be the same as a name of an existing element. For example use:
<xsl:variable name="vUrl" select="url" />
You could also check the next following sibling:
<xsl:template match="url-picker">
<xsl:variable name="url"><xsl:value-of select="./url" /></xsl:variable>
<xsl:value-of select="concat('"', $url, '"')" />
<xsl:if test="following-sibling::url-picker">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:template>
I'm not sure if it will work in your case, because I'm not sure of the current context where the url-picker
template is called, but you could add an xsl:if
...
<xsl:template match="url-picker">
<xsl:variable name="url"><xsl:value-of select="./url" /></xsl:variable>
<xsl:value-of select="concat('"', $url, '"')" />
<xsl:if test="not(position()=last())">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:template>
精彩评论