Write Relational Data to an XML File

The DataSet class can be used to read a relational database table and write this table to an XML file. This article shows you how you can write data from a database to an XML file using data set object.

You use WriteXml method to write a dataset data to an XML file.

In this sample example, first I create a dataset connection to the Northwind database. After that I create a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.

Once a dataset if filled with records, I call WriteXml method to write data to an XML file "CustTableDt.xml" in C:\ dir.

// create a connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = connString;
// create a data adapter
OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", myConnection);
// create a new dataset
DataSet ds = new DataSet();
// fill dataset
da.Fill(ds, "Customers");
// write dataset contents to an xml file by calling WriteXml method

Don't forget to include System.Data and System.Data.OleDb namespaces.

The portion of XML file looks like the following:

<?xml version="1.0" standalone="yes" ?>
- <NewDataSet>
- <myTable>
<CompanyName>Alfreds Futterkiste</CompanyName>
<ContactName>Maria Anders</ContactName>
<ContactTitle>Sales Representative</ContactTitle>
<Address>Obere Str. 57</Address>
- <myTable>