I want to add ‘,‘ only when it’s needed
I check <xsl:when test="$myvar!=''"> so it will not be like:
,one,two,three
but will be
one,two,three instead
but it says
Variable $myvar has not been declared;
<xsl:variable name="myvar">
<xsl:for-each select="$header/Packaging[@type='european']/UPCPackagingLevelCode">
<xsl:choose>
<xsl:when test="$myvar!=''">
<xsl:value-of select="concat(',',.)"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
You are indeed trying to use a variable before it is has been declared. You are referring to $myVar in the body of the variable declaration. $myVar won’t actually be declared until after the final closing xsl:variable
In this case, what you need to solve your problem is make use of the position function to determine if you are positioned on the first UPCPackagingLevelCode element.
So, instead of doing this….
Do this…
In fact, you could slightly simplify this, to use xsl:if instead of xsl:choose
And if you were using XSLT2.0, you could simplify the whole thing to just this