Parsing XML using C#

Time after time I find myself referring to a stack overflow post that I answered when I need to write code to parse XML quickly. I thought I would blog the code instead. If nothing else, it will save me a few clicks.

Considering I have the following XML:

        <Date>Wed Nov 03</Date>
        <Summary>Text Here</Summary>

Start off with a new using

using System.Xml.Linq;

Write a linq query to open your xml file. Get the descendants of the element that is grouping the elements you want to parse. Then do something with the result. In my case I am populating and returning a container object.

XDocument changesetXML = XDocument.Load(Server.MapPath(@"~\changesets.xml"));

return from changeset in changesetXML.Descendants("Changeset")
       select new ChangeSet
           Id = changeset.Element("id").Value,
           User = changeset.Element("User").Value,
           DateAdded = changeset.Element("Date").Value,
           Summary = changeset.Element("Summary").Value