Sunday, December 14, 2008

Xml to Object model using linq

Have you thought of loading xml into an object model by single line of code?
It is possible with the help of linq.Just you need to write a single statement to obtain xml 2 class object model conversion.
This post needs some basic understanding about Linq.You may get it by visiting this post.

Here is the Xml you are going to convert.
<?xml version="1.0" encoding="utf-8" ?>
<
Employees>
<
Employee ID="10">
<
Name>Joy</Name>
<
Designation>Sr Software Engg</Designation>
</
Employee>
<
Employee ID="12">
<
Name>ABC</Name>
<
Designation>Software Engg</Designation>
</
Employee>
<
Employee ID="1">
<
Name>George</Name>
<
Designation>Sr Software Engg</Designation>
</
Employee>
<
Employee ID="2">
<
Name>IJK</Name>
<
Designation>Testing Engg</Designation>
</
Employee>
<
Employee ID="3">
<
Name>XYZ</Name>
<
Designation>Team Leader</Designation>
</
Employee>
</
Employees>
The Employee class is given below
public class Employee
{
public string Name { get; set; }
public string Designation { get; set; }
}
The first step here is to load the xml into a XmlDocument.Then apply Linq.
Here goes the Linq Query.
XmlDocument xmldocument = new XmlDocument();
xmldocument.Load("../../employees.xml");
List<Employee> emps = (from i 
                       in xmldocument.ChildNodes[1].ChildNodes.Cast<XmlNode>()
                       select new Employee 
                       { 
                           Name = i.ChildNodes[0].InnerText ,
                           Designation = i.ChildNodes[1].InnerText 
                       }
                       ).ToList();

Download sample from here

No comments:

Post a Comment