开发者

Finding real and decimal numbers

I am using xslt1.0 for my html to xml conversion.

<xsl:variable name="margin">0</xsl:variable>

<xsl:if test="number($margin)">
<xsl:message>Its number</xsl:message>
</xsl:if>

This is my template wh开发者_开发知识库ich satisfying the condition and displaying message.If the variable margin's value is 0.5, then the condition becomes false.

How to write the condition which matches for decimals too?


     <xsl:template match="/">
      <xsl:variable name="margin">0</xsl:variable>

      <xsl:if test="number($margin)">
       <xsl:message>Its number</xsl:message>
      </xsl:if> </xsl:template>

This is my template which satisfying the condition and displaying message.
If the variable margin's value is 0.5, then the condition becomes false.

This is simply not true. Tested with 9 different xslt processors (both XSLT 1.0 and 2.0), the above code doesn't produce any message. On the other side, Any numeric value, different from 0 produces the message.

Explanation:

Due to the fact that number(0) is 0, and boolean(0) is false(), the test doesn't succeed .

Solution:

Use this XPath expression:

number($x) = number($x)

This expression evaluates to true() exactly when $x is a number and then it is equivalent to:

$x = $x

When $x is not a number, the XPath expression above evaluates to false() because it is equivalent to:

NaN = NaN

and by definition NaN is not equal to any other value, including NaN itself.


I tried your code (using MSXSL.EXE, which requires terminate="yes" on the message in order to see its output) and found, as I expected, the opposite to be true. When $margin is zero, the "if" doesn't happen, but if it is non-zero (e.g., 0.5), the "if" executes. This is because the test expression is evaluated with the same semantics as the "boolean()" function, which interprets the numeric value zero as false and any non-zero numeric value as true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜