Sometimes we need to export our DataSet or DataTable data to XML file. ASP.NET provides a simple WriteXml() method of DataTable or DataSet class. This method simply writes DataTable or DataSet data to the specified file. You can also achieve this by using StreamWriter class object with WriteXml() method of DataTable or DataSet class.
Let’s see how we can do it. You can also download sample code at the bottom of the article.
Don’t forget to use following namespaces in your code as these are necessary.
/* fetch data from database and populate DataSet or DataTable
or populate data into DataSet or DataTable in the code */
SqlConnection Myconn = new SqlConnection("MyConnectionString");
SqlCommand Mycommand = new SqlCommand();
Mycommand.CommandText = "SELECT * FROM MyTable";
Mycommand.CommandType = CommandType.Text;
Mycommand.Connection = Myconn;
SqlDataAdapter myAdapter = new SqlDataAdapter(Mycommand);
DataSet myDataSet = new DataSet();
DataTable myDataTable = new DataTable();
myDataTable = myDataSet.Tables;
// you can directly write a file with WriteXml() method
// or you can use StreamWriter object and write a file with WriteXml() method
StreamWriter MyWriter = new StreamWriter(Server.MapPath("~/Files/MyFile.xml"));