Tuesday, April 29, 2008

LINQ to XML

There's a lot you can do with LINQ to XML. It will be your alternative to selecting xml nodes using XPath queries. I'm going to show you just a little bit at a time.

Say you wanted to get all PersonName values from this xml:
<Persons>
  <Person>
    <PersonId>1</PersonId>
    <PersonName>Mark</PersonName>
  </Person>
  <Person>
    <PersonId>2</PersonId>
    <PersonName>Matt</PersonName>
  </Person>
</Persons>
You can simply write your LINQ like this:
XDocument ds = XDocument.Load("PersonsFile.xml");

var persons = from eachPerson in ds.Descendants("Person") 
select new 
{
    PersonName = eachPerson.Element("PersonName").Value
};
This is two lines of code. Notice the semicolon at the very end.

XDocument is like your new XmlDocument class. It loads an xml file.
LINQ is then used to find all elements (descendants) that are named "Person".

So what the heck is happening with that select new? Remember the post on anonymous types? That's what this LINQ to XML is creating; a collection of anonymous types (classes). The breakdown of what this LINQ statement is saying:
1. Give me a collection of elements that match "Person" which you can reference from the eachPerson variable.
2. Create an anonymous class and add a property called "PersonName".
3. "PersonName" is assigned a value from the eachPerson match.
4. Now add that new anonymous class to the var collection called "persons".

The result is a collection of typed objects that you can iterate through later on:
List<string> array = new List<string>();
foreach (var person in persons)
{
    array.Add(person.PersonName);
}

This is a whole different shift in thinking. To get used to it I suggest you write some code and create a bunch of anonymous classes until you are comfortable with that concept. Create anonymous classes, add properties. Access and use those properties and so on. Once you feel good and comfortable with that you can move on to learning more about LINQ.
More Info: MSDN: