XElement.XPathEvaluate无法正确评估指数数 [英] XElement.XPathEvaluate not evaluating exponential numbers correctly
问题描述
在我的C#程序中,我正在尝试解析的XML文件的一部分中加载一个System.Xml.Linq.Xelement
变量,并将其提供给各种XPath来评估使用XPathEvaluate()
方法的值.
In my C# Program, I am loading a System.Xml.Linq.Xelement
variable with a portion of an XML file I'm trying to parse and feeding it various XPaths to evaluate values for using the XPathEvaluate()
method.
我的挑战是我的XML将一些数字存储为指数数字,即使我读到XPath 2.0应该允许将它们理解为数字,但XPath还是忽略了它们.
My challenge is that my XML has some numbers stored as exponential numbers and the XPath is ignoring them even though I'm reading that XPath 2.0 should allow for these being understood to be numbers.
示例如下:
XML(childNode
):
<Parent>
<Vals id="Val1">
<abc>1.8</abc>
</Vals>
<Vals id="Val2">
<abc>4.8552829108959736E-5</abc>
<def>4.940657864520423E-4</def>
<ghi>0.1262403356384331</ghi>
<jkl>0.0</jkl>
</Vals>
</Parent>
XPath(myXPath
):
sum(Parent/Vals[@id="Val2"]/*[self::abc | self::def | self::ghi | self::jkl][number(.)=number(.)])
我的代码如下:
var value= childNode.XPathEvaluate(myXPath);
我希望该值是:
value = 4.8552829108959736E-5 + 4.940657864520423E-4 + 0.126240335638433 + 0
= 0.126782954253994
但是,我得到了:
value = 0.126240335638433 + 0
= 0.126240335638433
是否有任何想法可以在我的C#代码中解决?
Any thoughts about any way this can be fixed in my C# code?
推荐答案
XPath 2.0允许使用它们-但XPathEvaluate
仅支持XPath 1.0.这不是XElement
的缺点; .NET从来没有添加1.0以后的支持.
XPath 2.0 does allow them -- but XPathEvaluate
only supports XPath 1.0. This is not a shortcoming of XElement
; .NET never added support past 1.0.
如果您必须在此处使用XPath,请参见此列表以获得第三方支持.
If you must use XPath here, see this list for third-party support.
如果您不需要使用XPath本身进行计算,而只是在C#中寻找实现此目的的方法,那当然很简单:
If you don't need to do use XPath for the calculation per se but are just looking for a way to do this in C#, that's simple enough of course:
var value = x.XPathSelectElements(@"/Vals[@id=""Val2""]/*").Sum(s => (double) s);
但是如果Sum
部分应该从您可以传入的任意表达式中动态执行,那么您将需要一个完整的XPath处理器.
But if the Sum
part is supposed to be performed dynamically from arbitrary expressions you can pass in, you'll need a full XPath processor.
这篇关于XElement.XPathEvaluate无法正确评估指数数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!