Export DataTable To XML Using C#

ADO.NET DataTable and DataSet classes provides methods to export and save their data into XML files. 
 
Create an ASP.NET Web Forms application. On the default Web Form, place a button and on click event of the button, write the following code. 
 
First import the following namespaces:
  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.IO;  
Copy and paste the following code where you need data read and save into XML format. In this code below to make sure to change your database connection, that is conn. Learn more about SQL Connection here, Exploring ADO.NET SqlConnection.
 
Next, create and execute a SQL command. The following code uses a SELECT * statement from Table. Change table to your table name. The code gets data into a DataSet and then to a DataTable. DataTable.WriteXml method is responsible for saving data into an XML file.
  1. SqlCommand cmd = new SqlCommand("select * FROM [table]", conn);  
  2. SqlDataAdapter da = new SqlDataAdapter(cmd);  
  3. DataTable dt = new DataTable();  
  4. dt.TableName = "Records";  
  5. da.Fill(dt);  
  6. DataSet dS = new DataSet();  
  7. dS.DataSetName = "RecordSet";  
  8. dS.Tables.Add(dt);  
  9. StringWriter sw = new StringWriter();  
  10. dS.WriteXml(sw, XmlWriteMode.IgnoreSchema);  
  11. string s = sw.ToString();  
  12. string attachment = "attachment; filename=test.xml";  
  13. Response.ClearContent();  
  14. Response.ContentType = "application/xml";  
  15. Response.AddHeader("content-disposition", attachment);  
  16. Response.Write(s);  
  17. Response.End();  
Here is a detailed article, Export DataTable Data Into An XML File.