Caveman's Blog

My commitment to learning.

Linq: Read data from XML file

leave a comment »


In this post I will show you how easy it is to load data into objects from an XML file using Linq. Let us see how we can create two employee objects from the following XML data:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
    <id>1001</id>
    <title>Manager</title>
    <salary>4000</salary>
  </Employee>
  <Employee>
    <id>1002</id>
    <title>Supervisor</title>
    <salary>2000</salary>
  </Employee>
</Employees>

Loading this data is a two step process. Before we start reading our data we have to define a class that will hold the data for each record in the XML file. For this I will create an Employee class with three properties that corresponds to the three elements of the Employee node from the XML data.

    public class Employee
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public int Salary { get; set; }
    }

We are now ready to read the entire XML file using the following code. First we load the XML file into an XDocument object and then create a collection of Employee objects by parsing the XML data using Linq.

XDocument xmlDoc = XDocument.Load("./../../Data.xml");

Employees = (from command in xmlDoc.Descendants("Employee")
select new Employee
{
ID = Convert.ToInt32(command.Element("id").Value),
Title = command.Element("title").Value,
Salary = Convert.ToInt32(command.Element("salary").Value),
}).ToList<Employee>();

foreach (Employee e in Employees)
Console.WriteLine("ID:{0} Title: {1} Salary: {2}", e.ID, e.Title, e.Salary);

//You will need to include the following two namespaces for this code to work
//using System.Xml;
//using System.Xml.Linq;

At this point we should have two Employee objects in the Employee List object and here is the output from executing the above code.

Advertisements

Written by cavemansblog

October 1, 2011 at 1:14 am

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: