When XPath does not return a node or nodeset

When using an aggregate XPath function like sum or avg, you can't use the methods SelectSingleNode or SelectNodes of the XmlDocument object. The aggregate functions return a scalar value and not a node or node-set (hence the reason the methods can't be used).

A simple way around this is to use the XPathNavigator object.

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator exp = doc.CreateNavigator();
Object myVal = exp.Evaluate("sum(/xpath/expression)");

I'm no .NET expert so if you know of a better way to do this, let me know.

Published August 11, 2005 · Updated September 14, 2006
Categorized as dotNET
Short URL: https://snook.ca/s/398