I have the folowing xml code:
<weather-code>14 3</weather-code>
<weather-code>12</weather-code>
<weather-code>7 3 78</weather-code>
Now i'd like to only grab the first number of each node to set a background image. So for each node i have the folowing xslt:
<xsl:attribute name="style">
background-image:url('../icon_<xsl:value-of select="substring-before(weather-code, ' ')" />.png');
</xsl:attribute>
Problem is that substring before doesn't return anything when there's no space. Any easy way around this?
substring-before() Function — Returns the substring of the first argument before the first occurrence of the second argument in the first argument. If the second argument does not occur in the first argument, the substring-before() function returns an empty string.
Concat function in XSLT helps to concatenate two strings into single strings. The function Concat() takes any arguments that are not the string is been converted to strings. The cardinality function passed over here in each argument should satisfy zero or one function() respectively.
You can use xsl:when
and contains
:
<xsl:attribute name="style">
<xsl:choose>
<xsl:when test="contains(weather-code, ' ')">
background-image:url('../icon_<xsl:value-of select="substring-before(weather-code, ' ')" />.png');
</xsl:when>
<xsl:otherwise>background-image:url('../icon_<xsl:value-of select="weather-code" />.png');</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
You can make sure that there is always a space, maybe not the prettiest but at least it's compact :)
<xsl:value-of select="substring-before( concat( weather-code, ' ' ) , ' ' )" />
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