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?
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.
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