Microsoft Technology Journals by Abhimanyu K Vatsa

4 Sep 2012

Transforming Data Source objects into XML using LINQ - Part 9

This is ninth part of the ‘LINQ’ series posts that I have started from here. In the last post we explored customizing the LINQ’s ‘select’ statement to select subset of each source element. Now, in this post 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 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"

Remember to use ‘System.Xml.Linq’ namespace that supports XElement in LINQ. Now, it’s time to execute the above query as:

string XMLFileInformation = "<?xml version=\"1.0\"?>\n" + studentsToXML;

Output on Console: Here is what my above code generated for me.

<?xml version="1.0"?>
    <Name>Abhimanyu K Vatsa</Name>
    <Name>Deepak Kumar</Name>
    <Name>Mohit Kumar</Name>
    <Name>Geeta K</Name>

If you want to build an real xml file then use following line

File.AppendAllText("C:\\Database.xml", XMLFileInformation);

Remember to use ‘System.IO’ namespace to create xml file on disk. Now, open 'C drive' and file a new xml file named Database.xml.

Same way you can do this for outer data sources (not in-memory) too.

I hope you will find it useful. Thanks for reading.

Comment using Google Services (7 comments):

  1. Replies
    1. Thanks. learned all from you, so credit goes to you too sir :)

    2. Very useful, thanks!

  2. This comment has been removed by the author.

  3. nice job but i just do not understand this line as fllows....

    let x = String.Format("{0},{1},{2},{3}", student.Marks[0], student.Marks[1], student.Marks[2], student.Marks[3])