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 a data set object.
You use the 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 the Customer table. After that, I can fill a method to fill a dataset from the data adapter.
Once a dataset if filled with records, I call the WriteXml method to write data to an XML file "CustTableDt.xml" in C:\ dir.
  1. // create a connection string  
  2. string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";  
  3. OleDbConnection myConnection = new OleDbConnection();  
  4. myConnection.ConnectionString = connString;  
  5. // create a data adapter  
  6. OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", myConnection);  
  7. // create a new dataset  
  8. DataSet ds = new DataSet();  
  9. // fill dataset  
  10. da.Fill(ds, "Customers");  
  11. // write dataset contents to an xml file by calling WriteXml method  
  12. ds.WriteXml("C:\\CustTableDt.xml"); 
Don't forget to include System.Data and System.Data.OleDb namespaces.
The portion of XML file looks like the following:
  1. <?xml version="1.0" standalone="yes" ?>  
  2. <NewDataSet>  
  3.     - <myTable>  
  4.         <CustomerID>ALFKI</CustomerID>  
  5.         <CompanyName>Alfreds Futterkiste</CompanyName>  
  6.         <ContactName>Maria Anders</ContactName>  
  7.         <ContactTitle>Sales Representative</ContactTitle>  
  8.         <Address>Obere Str. 57</Address>  
  9.         <City>Berlin</City>  
  10.         <PostalCode>12209</PostalCode>  
  11.         <Country>Germany</Country>  
  12.         <Phone>030-0074321</Phone>  
  13.         <Fax>030-0076545</Fax>  
  14.     </myTable>  
  15.     - <myTable> 

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.