In this Article, we are exporting data from DataSet to XMl file. The below code uses dataset to take data from the database and populate the grid on the .aspx page and creates a xml file in the solution directory.
<connectionStrings>
<add name="cnStrMain" connectionString="CONNECTION STGRING" providerName="System.Data.Sqlclient"/>
</connectionStrings>
Add the connection string in the WEB.CONFIG file.
<add name="cnStrMain" connectionString="CONNECTION STGRING" providerName="System.Data.Sqlclient"/>
</connectionStrings>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnStrMain"].ConnectionString.ToString());
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn2XML_Click(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM MEMBERS where COMPANY_ID is not null";
command.CommandType = CommandType.Text;
command.Connection = sqlcn;
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "MEMBERS");
if (ds.Tables[0].Rows.Count > 0)
{
grdXML.DataSource = ds;
grdXML.DataBind();
}
// Get a StreamWriter object
StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/Testdo.xml"), false);
// Apply the WriteXml method to write an XML document
ds.WriteXml(xmlDoc);
xmlDoc.Close();
}
}