Monthly Archives: December 2012

Reading XML using C# Linq – Short and Simple

Reading an XML has become easier by new Linq to XML queries. It is as simple as querying a List though there are differences in query as per XML structure you are trying to read.

Here is simple way to parse/read/query an XML file in the following format.

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Babies>
  <Baby>
    <Name>Aabhas</Name>
    <Gender>M</Gender>
    <Meaning>Feeling</Meaning>
  </Baby>
  <Baby>
    <Name>Balwan</Name>
    <Gender>M</Gender>
    <Meaning>Strong</Meaning>
  </Baby>
  <Baby>
    <Name>Chandra</Name>
    <Gender>M</Gender>
    <Meaning>Moon</Meaning>
  </Baby>
</Babies>

Below is the C# class representation of XML file

public class Baby
{
 public string Name { get; set; }
 public string Meaning { get; set; }
 public string Gender{ get; set; }

}

Below is the C# code to read the nodes and reading it as List

XDocument xdoc = XDocument.Load(xmlFileName);
List<Baby> babies = new List<Baby>();
babies = (from b in xdoc.Descendants("Baby")
select new Baby() { Name = b.Element("Name").Value, Meaning = b.Element("Meaning").Value ,Gender=b.Element("Gender").Value }
).ToList();

Obviously we can apply search filter to the list and do all the possible list operations.
I did not provide any analysis for performance here as of now but will test and update this post later.

I hope it helps!

Advertisements