LINQ to XML – What I’ve been missing

Ok. You may laugh. I’ve just today used LINQ for the first time to parse an XML file, and I’m seriously blown away at how easy it was. I’m a little embarrassed, since LINQ has been available since .NET 3.5 was released around November 2007.

If you are like I was, (LINQ-less!!), I’ll give a brief introduction here. LINQ (Language INtegrated Query), is a component that adds native data querying capabilities to .NET languages. It can be used to read, parse and write XML files (and also SQL, which I may cover in a future post). Take a look at the example below to see how easy it is to use this technique to read data from an XML file.

Reading data from an XML file is a very common scenario. I always used .ini file as configuration files for any applications I wrote, but .NET doesn’t provide any built in support for .ini, and hence wants you to use XML.

Consider the following XML file:

In order to read this using LINQ to XML, you need to ensure you have specifed the correct header files:

using System.Linq;
using System.Xml.Linq;

Now for the easy part, here’s the code to read data from the XML file, and print out the values to the console:

XDocument xmlDoc = XDocument.Load(@"example.xml");
var servers = from server in xmlDoc.Descendants("server")
select new
     Name = server.Element("name").Value,
     IP = server.Element("ip").Value,
     Owner = server.Element("owner").Value,

foreach (var server in servers)
     Console.WriteLine("Server Name: " + server.Name);
     Console.WriteLine("Server IP: " + server.IP);
     Console.WriteLine("Server Owner: " + server.Owner);

Easy huh? The line beginning with ‘var servers=…‘ may look strange to you if you’ve never seen it before, (it did to me). This is an anonymous type declaration. If you’ve never heard of anonymous types in C#, MSDN has some great documentation here.

Happy coding.