Converting SQL Data Into an Xml Document Using ASP.NET

ASP.NET allows us to convert relational data from the database into a XML document. For it we have to use the XMLDataDocument class available in the System.Xml namespace. We require this when we want to create a web application that retrieves data about customers from the webshop Web Site from the SQL Server 2008 database. The retrieved data should be converted into the device independent format so that business partners can analyze the retrieved data. For this reason we need to retrieve relational data from the SQL Server database 2008.

Let's have a look at the following steps:

Step 1

First go to Visual Studio 2010.

Step 2

Now click on File -> New -> Web Site.

Step 3

Select the ASP.NET Web Site.

xc1.jpg

Step 4

Now give the name to your application and click on the ok button.

xc2.jpg

Step 5

Now add the XML server control to your Web Form by dragging and dropping it on the form.

xc3.jpg

Step 6

Now add the following code for the page load event of the Web Form.

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;

public
partial class Default2 : System.Web.UI.Page
{
   
protected void Page_Load(object sender, EventArgs e)
   
{
       
DataSet ds = new DataSet();
       
try
       
{
           
SqlConnection con = new SqlConnection("server=.;initial catalog=megha;uid=sa;pwd=wintellect");
           
con.Open();
           
SqlDataAdapter da = new SqlDataAdapter("select * from customer", con);
           
da.Fill(ds, "customer");
       
}
       
catch
       
{
           
Label1.Text = "Error while connecting to a database";      
       
}
       
XmlDataDocument doc = new XmlDataDocument(ds);
       
Xml1.Document = doc;
       
doc.Save(MapPath("Customers.xml"));
   
}
}

In this code we have added the three namespaces namely System.Data, System.Data.SqlClient and System.Xml.

Step 7

Now press F5 or click on the start debugging under the debug menu to run the application.

xc4.jpg

Step 8

The output will be like this:

 xc5.jpg