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

About saxenapraveen

I work with Microsoft and have 12 years of experience in developing,designing and leading reliable and scalable solutions for cloud and device ready businesses.

Posted on December 27, 2012, in .NET, Asp.Net WebForms, C#, XML. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: