Articles → ADO.NET → Convert Datatable To XML In C#
Convert Datatable To XML In C#
Code
using System.Data;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Name", typeof(string));
DataRow row1 = dt1.NewRow();
row1["Name"] = "Test name";
dt1.Rows.Add(row1);
DataTable dt2 = new DataTable();
dt2.Columns.Add("Address", typeof(string));
DataRow row2 = dt2.NewRow();
row2["Address"] = "Test address";
dt2.Rows.Add(row2);
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
string dsXml = ds.GetXml();
string xmlFile = @"c:\temp\test.xml";
using(StreamWriter fs = new StreamWriter(xmlFile)) // XML File Path
{
ds.WriteXml(fs);
}
}
}
}
Output
Click to Enlarge