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:
- using System.Data;
- using System.Data.SqlClient;
- 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.
- SqlCommand cmd = new SqlCommand("select * FROM [table]", conn);
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- dt.TableName = "Records";
- da.Fill(dt);
- DataSet dS = new DataSet();
- dS.DataSetName = "RecordSet";
- dS.Tables.Add(dt);
- StringWriter sw = new StringWriter();
- dS.WriteXml(sw, XmlWriteMode.IgnoreSchema);
- string s = sw.ToString();
- string attachment = "attachment; filename=test.xml";
- Response.ClearContent();
- Response.ContentType = "application/xml";
- Response.AddHeader("content-disposition", attachment);
- Response.Write(s);
- Response.End();
Here is a detailed article, Export DataTable Data Into An XML File.