代码之家  ›  专栏  ›  技术社区  ›  Jules Colle

xslt:前面的子字符串

  •  11
  • Jules Colle  · 技术社区  · 15 年前

    我有以下xml代码:

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

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

    问题是,在没有空格的情况下,substring before不会返回任何内容。有什么简单的办法吗?

    3 回复  |  直到 15 年前
        1
  •  24
  •   Oded    15 年前

    你可以用 xsl:when 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>
    
        2
  •  23
  •   Ledhund    15 年前

    你可以确保总有一个空间,也许不是最漂亮的,但至少它很紧凑:)

    <xsl:value-of select="substring-before( concat( weather-code, ' ' ) , ' ' )" />
    
        3
  •  1
  •   polygenelubricants    15 年前

    你可以用 functx:substring-before-if-contains

    functx:substring-before-if-contains 函数执行 substring-before , 如果不包含分隔符,则返回整个字符串 . 它不同于内置的 fn:substring-before 函数,如果找不到分隔符,则返回长度为零的字符串。

    the source code ,具体实现如下:

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