【问题标题】:Conditional variable select in XSLTXSLT 中的条件变量选择
【发布时间】:2013-10-08 23:51:26
【问题描述】:

如果值是数字,我希望变量具有元素的值,但如果不是,那么我希望变量具有值0

换句话说,在 XSLT 中是否有以下的简单等价物?

var foobar = is_numeric(element value) ? element value : 0

或者你会怎么写?

<xsl:variable name="foobar" select=" ? " />

【问题讨论】:

    标签: variables xslt xslt-2.0


    【解决方案1】:

    XPath 1.0:

    <xsl:variable name="foobar">
      <xsl:choose>
        <xsl:when test="number($value) = number($value)">
          <xsl:value-of select="$value"/>
        </xsl:when>
        <xsl:otherwise>0</xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    

    这个聪明的 number($value) = number($value) 数字测试的参考:Dimitre Novatchev's answer"Xpath test if is number" question

    【讨论】:

      【解决方案2】:

      在 XPath 2.0 中是的,您可以使用“castable as

      <xsl:variable name="foobar" as="xs:double"
         select="if (x castable as xs:double) then x else 0" />
      

      【讨论】:

        【解决方案3】:

        你可以使用:

        <xsl:variable name="x" 
                      select="(ELEMENT[. castable as xs:double], 0)[1]"/>
        

        <xsl:variable name="x" 
                      select="sum(ELEMENT[. castable as xs:double])"/>
        

        【讨论】:

        • (x, y) 在您的第一个示例中做了什么?
        • @Svish, (x, y) 形成了一个由xy 组成的序列,但是如果ELEMENT[. castable as xs:double] 的内容不是一个双精度值,那么ELEMENT[. castable as xs:double] 会产生一个空序列。 (ELEMENT, 0) 的序列或简单的序列 (0)。然后谓词[1] 选择ELEMENT0
        • @Svish 所以特别是如果在当前上下文中有多个 ELEMENT 孩子,那么我的方法将始终返回 0 (因为多个项目的序列不是 castable as xs:double ),而 Michael 的方法将返回第一个 ELEMENT 子节点,该子节点可以转换为 xs:double(在 (x, y)[1] 情况下)或所有此类 ELEMENTs 的总和(在 sum() 情况下),或 @ 987654342@ 如果它们都不能适当地转换。
        • 酷,感谢您的解释。我要去@IanRoberts,因为它最清楚地表达了我真正想要的东西。似乎不那么骇人听闻了,呵呵。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        相关资源
        最近更新 更多