Export Dataset Data To XML File

Introduction:

In this code you have to write the file name with the extension .xml and the code will create the xml file with that name and populate it.

Code:

using
System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

public
partial class ExportToXml : System.Web.UI.Page
{
   
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ExportImportCS"].ConnectionString);
    protected
void Page_Load(object sender, EventArgs e)
}

public void ConnectionXML()
{
   
SqlCommand command = new SqlCommand();
   
command.CommandText = "SELECT * FROM BookIssueDetails";
   
command.CommandType = CommandType.Text;
   
command.Connection = con;
   
SqlDataAdapter da = new SqlDataAdapter(command);
   
DataSet ds = new DataSet();
    
da.Fill(ds, "BookIssueDetails");
   
if (ds.Tables[0].Rows.Count > 0)
   
{
       
grdXML.DataSource = ds;
       
grdXML.DataBind();
   
}

    // Get a FileStream object
   
StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/FileTest/Testdo.xml"), false);
   
// Apply the WriteXml method to write an XML document
   
ds.WriteXml(xmlDoc);
   
xmlDoc.Close();
}

protected void btnExportToXml_Click(object sender, EventArgs e)
{
   
ConnectionXML();
}

Source code Page View

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportToXml.aspx.cs" Inherits="ExportToXml" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdXML" runat="server">
</asp:GridView>
</div>
<asp:Button ID="btnExportToXml" runat="server" OnClick="btnExportToXml_Click" Text="EXPORT XML" />
</form>
</body>
</html>

Up Next
    Ebook Download
    View all
    Learn
    View all