2010-06-23 3 views
10

Ho il codice XML folowing:XSLT: substring-before

<weather-code>14 3</weather-code> 
<weather-code>12</weather-code> 
<weather-code>7 3 78</weather-code> 

Ora vorrei afferrare solo il primo numero di ogni nodo per impostare un'immagine di sfondo. Così, per ogni nodo ho l'XSLT folowing:

<xsl:attribute name="style"> 
    background-image:url('../icon_<xsl:value-of select="substring-before(weather-code, ' ')" />.png'); 
</xsl:attribute> 

Il problema è che prima di sottostringa non restituisce nulla quando non c'è spazio. Un modo semplice per aggirare questo?

risposta

17

È possibile utilizzare xsl:when e 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> 
+0

+1: sarei andato allo stesso modo. – Manish

+0

I condizionali Xslt sono ICK! Mi piace la soluzione di Ledhund, ma questo è tecnicamente corretto. – Armstrongest

1

È possibile utilizzare functx:substring-before-if-contains

La funzione functx:substring-before-if-contains esegue substring-before, restituendo l'intera stringa, se non contiene il delimitatore. Si differenzia dalla funzione integrata fn:substring-before, che restituisce una stringa di lunghezza zero se il delimitatore non viene trovato.

Guardando the source code, è implementato come segue:

<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> 
+0

che xsl: la sequenza sembra utile. Ho già implementato il metodo di Oded, ma sicuramente cercherò di provarlo la prossima volta che affronterò qualcosa di simile. –

20

è possibile assicurarsi che ci sia sempre uno spazio, forse non la più bella, ma almeno è compatto :)

<xsl:value-of select="substring-before(concat(weather-code, ' ') , ' ')" /> 
+1

+1 perché è così compatto :) –

+0

+1 evita condizionali che portano ad altri problemi in un caso d'uso Ho il pensiero non lineare –

+0

+1. Mi piace. – Armstrongest