I sure do love linq
Code:
using System;
using System.Linq;
using System.Xml.Linq;
namespace GetSumFromXmlItems
{
class Program
{
static void Main(string[] args)
{
XDocument xDocument = XDocument.Parse(
"<items>" +
"<item displayInfoId=\"63690\" durability=\"60\" level=\"251\" />" +
"<item displayInfoId=\"64272\" durability=\"0\" level=\"264\"/>" +
"</items>"
);
var levels = xDocument.Element("items").Elements("item")
.Select(i => int.Parse(i.Attribute("level").Value));
int levelsSum = levels.Sum();
Console.WriteLine(levelsSum);
}
}
}
The important namespace are
Code:
using System.Linq;
using System.Xml.Linq;
System.Xml.Linq exposes the XDocument, XElement, and XNode classes, which are newer (and far superior) to the older classes for XML parsing/manipulation like XmlReader.
Code:
var levels = xDocument.Element("items").Elements("item")
returns a sequence (of type IEnumerable<XElement>) that we can use the goodies in System.Linq on (for this example, Linq to Objects).
the var keyword stands for an anonymous type, meaning giving it an explicit type is deferred until it's needed (in this case it's never specified, so it stays an IEnumerable<int>) which is inferred from this line:
Code:
.Select(i => int.Parse(i.Attribute("level").Value));
At this point in the code, we've exposed an anonymous type (of type var) that we're defining as an int. The type of int is inferred by the type of return value from the int.Parse() method.
Code:
int levelsSum = levels.Sum();
Console.WriteLine(levelsSum);
When using .Net, never attempt to hack together a solution to a trivial problem without checking if one already exists. This time, we can thank the Sum() method, which sums together any (IEnumerable) sequence of numerical data.