开发者

xslt 1.0 how to test for numbers

开发者 https://www.devze.com 2023-03-24 10:45 出处:网络
How can I test if value of element is a number / is castable to number? What I need to do is to copy value if it is a number, and substitute it wi开发者_开发问答th 99 if it is a stringstring(number($

How can I test if value of element is a number / is castable to number?

What I need to do is to copy value if it is a number, and substitute it wi开发者_开发问答th 99 if it is a string


string(number($x)) = 'NaN' tests whether $x is castable to a number.


You could use the 'number' function -

http://www.zvon.org/xxl/XSLTreference/Output/function_number.html


In addition to the correct answer by @Michael Kay:

number($x) = number($x)

this expression is true() exactly when $x is castable to a number

Here we use the fact that:

  1. If $x isn't a number, then number($x) by definition is NaN

  2. NaN isn't equal to any value, even to NaN

Now, your final question:

What I need to do is to copy value if it is a number, and substitute it with 99 if it is a string

Use:

  $x * (number($x) = number($x))
+
  99 * not(number($x) = number($x))

Explanation: A boolean is converted to number (true() --> 1, false() --> 0) when part of a numeric expression. In the above expression one of the arguments of + will be 0 and one will be 1 depending on whether $x isn't/is a number.

0

精彩评论

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