Database table to XML file

Here I give an example of how we can create a XML file from a database table.

In this example, I had populated a dropdownlist with the tables in a database. Then I choose a table from the list, which needs to be generated as a XML file.

Listing all the tables in the Database

Listing all the tables in the Database

We will generate the XML file in the ‘SelectedIndexChanged’ event of the DropDownList.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();

//Create the connection object
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings[ "LMSConnectionString"].ToString());


string strQuery = "Select * from " + DropDownList1.SelectedItem.Text;

SqlCommand sqlCmd = new SqlCommand(strQuery, sqlConn);
SqlDataAdapter sqlAdptr = new SqlDataAdapter(sqlCmd);
sqlAdptr.Fill(ds);


XmlDataDocument doc = new XmlDataDocument(ds);


doc.Save(MapPath(DropDownList1.SelectedItem.Text+".xml"));
//The name of the XML file to be generated
}
catch{ }
}

The above code will generate an XML file with the same name of the database table selected, in the root directory.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: