Home > Code > LINQ > Convert DataTable to XML using LINQ

Convert DataTable to XML using LINQ

by Thamil   on May 26, 2011   Category: LINQ   |  Views: 7475    |  Points: 25   |  Gold 


Sometimes you may have a situation like convert DataTable to xml file, in this situation LINQ technique is used to convert DataTable to desired xml format as shown below.

Fill Datatable with enough data
protected void CreateXML_Click(object sender, EventArgs e)
{
try
{
DataTable dtEmploye = new DataTable();
dtEmploye.Columns.Add("EMPLOYEENO");
dtEmploye.Columns.Add("NAME");
dtEmploye.Columns.Add("ADDRESS");
dtEmploye.Columns.Add("PHONE");
dtEmploye.Columns.Add("REMARKS");

DataRow rw = dtEmploye.NewRow();
rw[0] = "1";
rw[1] = "JOHN";
rw[2] = "CANADA";
rw[3] = "323555345";
rw[4] = "No Remarks";
dtEmploye.Rows.Add(rw);

DataRow rw1 = dtEmploye.NewRow();
rw1[0] = "2";
rw1[1] = "KENNY";
rw1[2] = "INDIA";
rw1[3] = "43534534";
rw1[4] = "Test";
dtEmploye.Rows.Add(rw1);
string str = GetEmployee(dtEmploye);
Response.Write(str);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

Convert into XML file using LINQ query.
public string GetEmployee(DataTable dt)
{
try
{
XDocument Employee = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
new XElement("COMPNAY", from cust in dt.AsEnumerable()
select new XElement("EMPLOYEE",
new XElement("NO", cust["EMPLOYEENO"]),
new XElement("Name", cust["NAME"]),
new XElement("Address", cust["ADDRESS"]),
new XElement("Phone", cust["Phone"]),
new XElement("Remarks", cust["Remarks"])
)));

return Employee.ToString();
}
catch (Exception ex)
{
return string.Empty;
throw ex;
}
}




Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts