In this blog, we Generate XML File From SQL
Database Using C#.
Creating
Table in SQL Server Database
Now create a table named UserDetail
with the columns UserId and UserName. The table looks like as below.
Now insert
some data into the table.
Now creating a new web
application project in Visual Studio 2010. Now add the following namespace.
using
System.Data.SqlClient;
using
System.Data;
using
System.Xml;
Now write the connection string to connect to the database.
string
strConnection = "Data Source=.; uid=sa;
pwd=wintellect;database=Rohatash;";
Let's take
a closer look at using Generating XML files from SQL Database within the .NET
Framework.
Creating a new web application project in Visual Studio 2010.
Drag and Drop
a Button and Label control to the form and make a link in Label control to show
the XML file.
For a sample design your aspx page might be like this.
<asp:Button
ID="Button1" runat="server"
onclick="Button1_Click"
Text="Save"
/>
<asp:Label
ID="LabelMessage"
runat="server"
ForeColor ="Red"
Text="ShowMessage"></asp:Label>
In Codebehind write the following code on the Button Event.
Codebehind
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Data.SqlClient;
using
System.Data;
using
System.Xml;
namespace
WebApplication119
{
public partial
class WebForm1
: System.Web.UI.Page
{
protected void
Page_Load(object sender,
EventArgs e)
{
}
protected void
Button1_Click(object sender,
EventArgs e)
{
SqlConnection con =
new SqlConnection("Data
Source=.; uid=sa; pwd=wintellect;database=Rohatash;");
string strSQL =
"Select UserId, UserName from UserDetail";
SqlDataAdapter dt =
new SqlDataAdapter(strSQL, con);
DataSet ds = new
DataSet();
dt.Fill (ds,"UserDetail");
ds.WriteXml(Server.MapPath("emp_xml_file.xml"));
LabelMessage.Text = "<a href=emp_xml_file.xml> XML
file</a>";
}
}
}
Now run the application and test it.
Now click on the Button link will be generate to show
the XML file.
Now click on the link to show the XML file.