Hi,
This is an interesting simple but very useful stuff. XML Manipulating is a task that some times consumes a lots of time depending on the complexity of XML. But this post is discussing about an interesting way to manipulate XML content in C#. Good way to learn things is learning through example. Let’s look at a very simple example to a simple XML file.
Creating XML File
Let’s create a simple xml file called Students.xml
<Students>
<Student>
<Id>Stu001</Id>
<Name>Sam</Name>
</Student>
<Student>
<Id>Stu002</Id>
<Name>John</Name>
</Student>
<Student>
<Id>Stu003</Id>
<Name>Tom</Name>
</Student>
</Students>
Let’s Read
Now let’s read our xml file with LINQ.
//Loading XML Document
XDocument Students = XDocument.Load(@"Students.xml");
//get all student elements and assign them to Anonymous Object
var StudentList = from x in Students.Descendants("Student")
select new
{
Id=x.Element("Id").Value,
Name = x.Element("Name").Value
};
//Iterate thorugh the results set to print
foreach (var student in StudentList)
{
Console.WriteLine(student.Id.ToString());
Console.WriteLine(student.Name.ToString());
Console.WriteLine("----------------------");
}
//Console ReadLine to keep the console window open after execution
Console.ReadLine();
Let’s dig into the code
First we are creating an XDocument to load the particular XML file from directory
XDocument Students = XDocument.Load(@"Students.xml");
Now get all the descendants of Student XML element and assign them to a Anonymous (Not Type Specific) object.
var StudentList = from x in Students.Descendants("Student")
select new
{
Id=x.Element("Id").Value,
Name = x.Element("Name").Value
};
Finally iterate through the results set and print them out
foreach (var student in StudentList)
{
Console.WriteLine(student.Id.ToString());
Console.WriteLine(student.Name.ToString());
Console.WriteLine("----------------------");
}
The above code will read the xml file and displays the results in the console.

XML Details in Console Window
Download Source Code
Like a piece of cake. Isn’t it ? 
Yes. We are done. Happy Coding
Recent Comments