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.
-
- string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
- OleDbConnection myConnection = new OleDbConnection();
- myConnection.ConnectionString = connString;
-
- OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", myConnection);
-
- DataSet ds = new DataSet();
-
- da.Fill(ds, "Customers");
-
- 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:
- <?xml version="1.0" standalone="yes" ?>
- - <NewDataSet>
- - <myTable>
- <CustomerID>ALFKI</CustomerID>
- <CompanyName>Alfreds Futterkiste</CompanyName>
- <ContactName>Maria Anders</ContactName>
- <ContactTitle>Sales Representative</ContactTitle>
- <Address>Obere Str. 57</Address>
- <City>Berlin</City>
- <PostalCode>12209</PostalCode>
- <Country>Germany</Country>
- <Phone>030-0074321</Phone>
- <Fax>030-0076545</Fax>
- </myTable>
- - <myTable>