Question

I have an xml file as such

<root>
<segmentNameA attributeName="10" />
<segmentNameB attributeName="50" />
</root>

Here's my code:

XPathDocument xPathDocument = new XPathDocument(analysisFileToProcess);
XPathNavigator  Navigator = xPathDocument.CreateNavigator();

I would like to get the sum of all the attributeName attributes (10 + 50).

Here's what I do

var sum /*want to obtain 60*/ = Navigator.Select(Navigator.Compile("sum(/root/*[self::segmentNameA or self::segmentNameB]/@attributeName)"));

I get an expression "has an invalid token".

However, when I do this

var nodes = Navigator.Select(Navigator.Compile("/root/*[self::segmentNameA or self::segmentNameB]"));

I get all the nodes which contain the attribute I'd like to sum on.

And when I do that

var nodes = Navigator.Select(Navigator.Compile("/root/*[self::segmentNameA or self::segmentNameB]/@attributeName"));

I get the list of the attributes. Why can't I use the sum function on this?

Could someone please point out to me what I am doing wrong?

Was it helpful?

Solution

It happens, because XPath expression must evaluate to a node-set.
Use Evaluate method instead:

var sum = (double)Navigator.Evaluate("sum(/root/*[self::segmentNameA or self::segmentNameB]/@attributeName)");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top