XElement.XPathEvaluate not evaluating exponential

2019-08-08 15:04发布

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.

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.

A sample would look as follows:

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(.)])

and my code looks like:

var value= childNode.XPathEvaluate(myXPath);

I would expect the value to be:

value = 4.8552829108959736E-5 + 4.940657864520423E-4 + 0.126240335638433 + 0
      = 0.126782954253994

But, rather I get:

value = 0.126240335638433 + 0
      = 0.126240335638433

Any thoughts about any way this can be fixed in my C# code?

1条回答
贪生不怕死
2楼-- · 2019-08-08 15:28

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.

If you must use XPath here, see this list for third-party support.

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);

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.

查看更多
登录 后发表回答