tags:

views:

184

answers:

1

I've got an XPathNavigator at the root of a document. Several levels down, there's a group of numeric values that I want to sum. I could always loop through the nodes and add them myself, but since I knew the XPath spec included a sum function, I decided to try to use that. I'm running into an error.

System.Xml.XPath.XPathException - Expression must evaluate to a node-set.

Here's my code.

XPathDocument doc = new XPathDocument(new StringReader(myLiteralXML));
XPathNavigator nav = doc.CreateNavigator();
string myXPath = "sum(/root/level1/level2/elementsToAdd)";
XPathNavigator sumNode = nav.SelectSingleNode(myXPath);

I expected sumNode.Value to give me my sum (as a string). But instead I get the exception listed above when I try to populate sumNode.

I know my XPath is valid (or at least XMLSpy says it is). Can I not use the XPath functions on an XPathNavigator? Am I just doing it wrong?

(Also, just curious, am I wasting my time on a dead-end approach nobody's using, and risking not being able to figure out a year from now what this is doing?)

+5  A: 

Try this instead:

XPathNavigator sumNode = nav.Evaluate(myXPath);

The XPathNavigator.Evaluate method is defined as:

Evaluates the specified XPath expression and returns the typed result.

as opposed to the XPathNavigator.SelectSingleNode method which is designed to only return nodes.

Andrew Hare
Never knew that was there. Thanks.
John M Gant