Basically I have a string created from a loop separated by commas eg. A,B,C, I want to get rid of the last comma.
<xsl:variable name="myConcatString">
<xsl:for-each select="valueinElement">
<xsl:value-of select="@attributeValue"/>,
</xsl:for-each>
</xsl:variable>
<xsl:variable name="valueLength" select="string-length($myConcatString)-1"/>
<xsl:value-of select="substring($myConcatString,1,$valueLength)"/>
Now the last line should give me A,B,C without the "," in the last. Can someone tell me what is going wrong?
You're outputting whitespace because of the way you've formatted the XML. You can fix it in two ways. One is to just remove the formatting:
<xsl:for-each select="valueinElement"><xsl:value-of select="@attributeValue"/>,</xsl:for-each>
The other, more robust way is to change the way you're handling whitespace:
<xsl:for-each select="valueinElement">
<xsl:value-of select="@attributeValue"/>
<xsl:text>,</xsl:text>
</xsl:for-each>
What this is doing is treating just the comma as an element so that it ignores the surrounding whitespace, instead of treating all of the whitespace inside of the for-each loop as part of the output.
For reference, I ran the above XSLT snippets against the following XML file:
<root>
<valueinElement attributeValue="dogs"/>
<valueinElement attributeValue="cats"/>
<valueinElement attributeValue="mice"/>
<valueinElement attributeValue="lasers"/>
<valueinElement attributeValue="frogs"/>
</root>
And got the following output in both cases:
dogs,cats,mice,lasers,frogs
Just use this replace, it will correct your output.
<xsl:value-of select="substring($myConcatString,1,$valueLength)"/>
with
<xsl:value-of select="substring($myConcatString,0,$valueLength)"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With