【问题标题】:xslt: substring-beforexslt:子字符串之前
【发布时间】:2011-03-07 05:18:01
【问题描述】:

我有以下 xml 代码:

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

现在我只想抓取每个节点的第一个数字来设置背景图像。因此,对于每个节点,我都有以下 xslt:

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

问题是当没有空格时,之前的子字符串不会返回任何内容。有什么简单的方法吗?

【问题讨论】:

    标签: xslt substring


    【解决方案1】:

    您可以使用xsl:whencontains

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

    【讨论】:

    • Xslt 条件是 ICK!我喜欢 Ledhun 的解决方案,但这在技术上是正确的。
    【解决方案2】:

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

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

    【讨论】:

    • +1 避免了在我的用例中导致其他问题的条件
    • 如果您在使用不支持 substring-before-if-contains 的早期版本 xml 解析器时遇到困难,这也非常有用。
    【解决方案3】:

    您可以使用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>
    

    【讨论】:

    • xsl:sequence 看起来很有用。我已经实现了 Oded 的方法,但下次遇到类似情况时,我一定会尝试一下。
    猜你喜欢
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多