Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt: substring-before

Tags:

substring

xslt

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?

like image 693
Jules Colle Avatar asked Jun 23 '10 08:06

Jules Colle


People also ask

What is substring before in XSLT?

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.

How do I concatenate in XSLT?

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.


2 Answers

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>
like image 95
Oded Avatar answered Oct 19 '22 18:10

Oded


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, ' ' ) , ' ' )" />
like image 33
Ledhund Avatar answered Oct 19 '22 18:10

Ledhund