Convert Datatable to XML String using LINQ

Well there are other ways to achieve the same functionality but with LINQ it becomes a bit easier with minimum piece of code. So let us start with the topic.

Open Visual Studio. Create a new Web Application File. Add a new webpage.

Add a new webpage

Copy the below code in the code behind of the added page.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if(!Page.IsPostBack)  
  4.     {  
  5.         GenerateXMLString();  
  6.     }  
  7. }  
  8. protected void GenerateXMLString()  
  9. {  
  10.     DataTable dt = null;  
  11.     try  
  12.     {  
  13.         dt = new DataTable();  
  14.         dt.Columns.Add("StudentID"typeof (int));  
  15.         dt.Columns.Add("Name"typeof (string));  
  16.         dt.Columns.Add("Marks"typeof (int));  
  17.         DataRow dr = dt.NewRow();  
  18.         dr[0] = 1;  
  19.         dr[1] = "John Smith";  
  20.         dr[2] = 200;  
  21.         dt.Rows.Add(dr);  
  22.         DataRow dr1 = dt.NewRow();  
  23.         dr1[0] = 2;  
  24.         dr1[1] = "Mark Johnson";  
  25.         dr1[2] = 300;  
  26.         dt.Rows.Add(dr1);  
  27.         XDocument stud = new XDocument(new XDeclaration("1.0""utf-8""true"), new XElement("STUDENTS", from stu in dt.AsEnumerable() select new XElement("STUDENT"new XElement("StudentID", stu["StudentID"]), new XElement("Name", stu["Name"]), new XElement("Marks", stu["Marks"]))));  
  28.         string _encodedXML = string.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(stud));  
  29.         Response.Write(_encodedXML.ToString());  
  30.     }  
  31.     catch(Exception Ex)  
  32.     {  
  33.         throw Ex;  
  34.     }  
  35. }  
In the above example we have created a datatable, populated the same with two records. Now using LINQ we have created the XDocument class object and defined XElement in it. XElement are added as per the structure of the XML required. Since we will not get the XML format on the page without encoding so we have encoded the string prior to displaying on the webpage.

When we run the code we get the following output.

Code

This is how we can convert datatable to XML using LINQ.

Ebook Download
View all
Learn
View all