How can I check if a node value is a number using XPath?
Any ideas?
To determine if some value is a number, one has to use the first XPath expression. The boolean function converts its argument to a boolean as follows: a number is true if and only if it is neither positive or negative zero nor NaN.
Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit)
number(): XPath number function converting string to a number. floor(): XPath foor function return largest integer round value that is equal to or less then to a parameter value. Another way we can say last round value that value return of the function. eg. FLOOR(10.45) return 10.
XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.
Test the value against NaN:
<xsl:if test="string(number(myNode)) != 'NaN'"> <!-- myNode is a number --> </xsl:if>
This is a shorter version (thanks @Alejandro):
<xsl:if test="number(myNode) = myNode"> <!-- myNode is a number --> </xsl:if>
The shortest possible way to test if the value contained in a variable $v
can be used as a number is:
number($v) = number($v)
You only need to substitute the $v
above with the expression whose value you want to test.
Explanation:
number($v) = number($v)
is obviously true, if $v
is a number, or a string that represents a number.
It is true also for a boolean value, because a number(true())
is 1 and number(false)
is 0.
Whenever $v
cannot be used as a number, then number($v)
is NaN
and NaN is not equal to any other value, even to itself.
Thus, the above expression is true only for $v
whose value can be used as a number, and false otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With