Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring,string-length function in xslt

Tags:

xslt

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?

like image 527
chugh97 Avatar asked Aug 08 '26 01:08

chugh97


2 Answers

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
like image 95
Welbog Avatar answered Aug 10 '26 19:08

Welbog


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)"/>
like image 41
user1910087 Avatar answered Aug 10 '26 18:08

user1910087