Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why XPATH count function returns a double instead of int?

Tags:

c#

xpath

The following fragment of code produces an InvalidCastException.

    static int XPathCount()
    {
        var doc = new XmlDocument();
        doc.LoadXml(
        @"<root>
             <item>value1</item>
             <item>value2</item>
             <item>value3</item>
          </root>");

        var navigator = doc.CreateNavigator();
        var expression = navigator.Compile("count(//item)");
        var count = navigator.Evaluate(expression);
        return (int) count;
    }

I was surprised of this behavior so I look the count() function into the XPATH specification:

The count function returns the number of nodes in the argument node-set.

So far so good but, what is a number? The answer is in the same specification:

number (a floating-point number)

Apparently this has been fixed in XPATH 2.0 to return an xs:integer but I still curious about this.

Does anyone knows why W3C decided to use a decimal number for the count() function?

like image 881
michelgb Avatar asked Sep 16 '25 18:09

michelgb


1 Answers

It's not a decimal. In XPath 1.0 it's an IEEE double-precision floating point number, in XPath 2.0 it's an integer.

XPath 1.0 has a single numeric type for the same reason Javascript does: in a weakly, dynamically typed language it makes considerable sense. Also, at the time XPath 1.0 was designed, Javascript was considered the primary candidate for the host language, which is why the data types are aligned with Javascript.

If you've only got one numeric type available, then that's what count() has to return.

like image 51
Michael Kay Avatar answered Sep 18 '25 09:09

Michael Kay