Transforming Data Source Objects Into XML Using LINQ: Part 9

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"


Remember to use the "System.Xml.Linq" namespace that supports XElement in LINQ. Now, it's time to execute the preceding query as:

 

string XMLFileInformation = "<?xml version=\"1.0\"?>\n" + studentsToXML;
Console.WriteLine(XMLFileInformation);


Output on Console:

 

<?xml version="1.0"?>

<School>

  <Student>

    <ID>1</ID>

    <Name>Abhimanyu K Vatsa</Name>

    <Address>Bokaro</Address>

    <Marks>97,92,81,90</Marks>

  </Student>

  <Student>

    <ID>2</ID>

    <Name>Deepak Kumar</Name>

    <Address>Dhanbad</Address>

    <Marks>70,56,87,69</Marks>

  </Student>

  <Student>

    <ID>3</ID>

    <Name>Mohit Kumar</Name>

    <Address>Dhanbad</Address>

    <Marks>78,76,81,56</Marks>

  </Student>

  <Student>

    <ID>4</ID>

    <Name>Geeta K</Name>

    <Address>Bokaro</Address>

    <Marks>95,81,54,67</Marks>

  </Student>

</School>


If you want to build a real XML file then use the following line:
 

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

Remember to use the "System.IO" namespace to create the XML file on disk. Now, open the C drive and file a new XML file named Database.xml.
 

In the same manner you can do this for outer data sources (not in-memory) too.
 

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

Up Next
    Ebook Download
    View all
    Learn
    View all