Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath test if node value is number

Tags:

xpath

How can I check if a node value is a number using XPath?

Any ideas?

like image 733
Harold Sota Avatar asked Oct 04 '10 10:10

Harold Sota


People also ask

How do you check if the value is a number in XSLT?

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.

What is Number () in XSLT?

Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit)

What is XPath number function?

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.

What is XPath expression in XML?

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.


2 Answers

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> 
like image 128
Oded Avatar answered Jan 08 '23 01:01

Oded


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.

like image 41
Dimitre Novatchev Avatar answered Jan 08 '23 00:01

Dimitre Novatchev