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" ?>

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 }

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!


About saxenapraveen

I have 14 years of experience in enterprise software development,designing and leading team to provide 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: Logo

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: