tags:

views:

222

answers:

2

I have an XML document and I would like to sum all elements of a specific name. How do I do this?

+1  A: 

You can start with the following code, which sums the value of specificName elements anywhere in the document (Descendants returns a collection of all elements with the specified name, regardless how deeply nested they are):

var doc = XDocument.Load("doc.xml");
var sum = (from nd in doc.Descendants("specificName")
           select Int32.Parse(nd.Value)).Sum();

Alternatively, if you don't want to use the query syntax, you could write something like:

var sum = doc.Descendants("specificName").Sum(nd => 
            Int32.Parse(nd.Value));

The examples assume that the value is stored as a text inside the element and that it is an integer.

Tomas Petricek
Also, you don't have to parse the element value like that, there is an operator overload that allows you to simply cast the element as its contained type. i.e. select (int)nd;
Tim Jarvis
Nice! thanks for pointing this out.
Tomas Petricek
A: 

Suppose this is your XML:

<nodes>
     <reading c='1'>17</reading>
     <reading c='2'>18</reading>
     <reading c='3'>19</reading>
     <reading c='4'>21</reading>
     <reading c='5'>4</reading>
     <reading c='6'>3</reading>
     <reading c='7'>7</reading>
</nodes>

Then use this code to sum the values of the reading elements:

public void Run()
{
    XDocument doc = XDocument.Load(fileToLoad);
    System.Console.WriteLine("\nSumming:");
    var sum = doc.Element("nodes")
                 .Elements("reading")
                 .Sum(n => int.Parse(n.Value));

    Console.WriteLine("  {0}", sum);
}
Cheeso