2

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?

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
G. Abitbol
  • 189
  • 1
  • 1
  • 8

1 Answers1

1

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)");
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • Indeed, edited, thanks for the pointer (still does not work though). – G. Abitbol Jun 12 '13 at 21:19
  • Kirill, now that I think of it, I received this error message, and even though it's pretty straight forward, I did not think of using other methods on my Navigator...it now works like a charm. Thanks a lot. – G. Abitbol Jun 13 '13 at 06:20