This is ninth part of the "LINQ" series of articles that I have started from here. In the previous article we explored customizing the LINQ's "select" statement to select a subset of each source element. Now, in this article you will learn how to transform data source objects into XML.
In-Memory Data Sources
Let's have some in-memory data:
List<Student> students = new List<Student>()
{
new Student { ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks= new List<int> {97, 92, 81, 90}},
new Student { ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks= new List<int> {70, 56, 87, 69}},
new Student { ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks= new List<int> {78, 76, 81, 56}},
new Student { ID=4, Name="Geeta K", Address="Bokaro", Marks= new List<int> {95, 81, 54, 67}}
};
Once we have in-memory data, we can create a query on it to generate XML tags and its data as given below:
var studentsToXML = new XElement("School",
from student in students
let x = String.Format("{0},{1},{2},{3}", student.Marks[0], student.Marks[1], student.Marks[2], student.Marks[3])
select new XElement("Student",
new XElement("ID", student.ID),
new XElement("Name", student.Name),
new XElement("Address", student.Address),
new XElement("Marks", x)
) //end of "student"
); //end of "Root"

Join the conversation! Your thoughts help the community grow.