tags:

views:

45

answers:

3

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?

+2  A: 

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>
Oded
+1: I would have gone the same way.
Manish
+1  A: 

You can use functx:substring-before-if-contains

The functx:substring-before-if-contains function performs substring-before, returning the entire string if it does not contain the delimiter. It differs from the built-in fn:substring-before function, which returns a zero-length string if the delimiter is not found.

Looking at the source code, it's implemented as follows:

<xsl:function name="functx:substring-before-if-contains" as="xs:string?">
<xsl:param name="arg" as="xs:string?"/>
<xsl:param name="delim" as="xs:string"/>
<xsl:sequence select=
  "if (contains($arg,$delim)) then substring-before($arg,$delim) else $arg"/>
</xsl:function>
polygenelubricants
that xsl:sequence thing looks useful. I have already implemented Oded's method, but i surely will give this a try next time a face something similar.
Jules
+2  A: 

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, ' ' ) , ' ' )" />
Ledhund
+1 cause it's so compact :)
Jules