8

I want a variable to have the value of an element if the value is numeric, but if it's not then I want the variable to have the value 0.

In other words, is there a simple equivalent of the following in XSLT?

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

Or how would you write this?

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

3 回答 3

15

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“Xpath test if is number”问题的回答。

于 2013-10-02T15:27:07.447 回答
9

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

<xsl:variable name="foobar" as="xs:double"
   select="if (x castable as xs:double) then x else 0" />
于 2013-10-02T14:42:53.207 回答
6

你可以使用:

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

或者

<xsl:variable name="x" 
              select="sum(ELEMENT[. castable as xs:double])"/>
于 2013-10-02T20:18:12.960 回答