Getting Started with Linq to XML

I was out at a customer site a few weeks ago and needed to whip up a quick program to extract a large number of values from an XML document. To me, the obvious way to accomplish this task was to write a quick application to read the XML, parse the values, and write them to a separate document. Linq to XML made this cumbersome task very easy, and I was reminded of just how amazing Linq to XML really is.

Linq to XML is one of the best things to happen to XML in recent history, but I think there are still a lot of developers out there who are either not familiar with Linq or are just comfortable working with XML using the same techniques that they always have. I haven’t done an extensive amount of XML processing in my career, but I haven’t exactly been a stranger to it, either. In my opinion Linq to XML makes working with XML downright trivial. If you haven’t looked into it, I definitely recommend that you do!

For the purposes of demonstration, consider an XML file “data.xml” with the following contents:

<Library>
  <Books>
    <Book>
      <Title>A Study in Scarlet</Title>
      <Author>Sir Arthur Conan Doyle</Author>
    </Book>
    <Book>
      <Title>A Thief in the Night</Title>
      <Author>E. W. Hornung</Author>
    </Book>
  </Books>
</Library>

Using Linq to XML, you can write code to parse the contents of the file into easy-to-use objects.

var xml = XDocument.Load(@"data.xml");
var data = from n in xml.Descendants("Book")
           select new
           {
               Author = n.Element("Author").Value,
               Title = n.Element("Title").Value
           };

foreach (var d in data)
    Console.WriteLine("{0},{1}", d.Title, d.Author);

Looking for a specific value in the XML? Just modify your Linq query!

var xml = XDocument.Load(@"data.xml");
var data = from n in xml.Descendants("Book")
           where n.Element("Author").Value == "E. W. Hornung"
           select new
           {
               Author = n.Element("Author").Value,
               Title = n.Element("Title").Value
           };

So cool!

Advertisement
%d bloggers like this: