9.1. Using an XML File to Save and Load a DataSet or a DataTable

Problem

You need to save a DataSet or DataTable as an XML file and create a DataSet or DataTable from an XML file.

Solution

Use the XmlTextWriter and XmlTextReader classes together with the WriteXml() and ReadXml() methods of the DataSet and DataTable classes.

The solution creates a DataSet containing a subset of data from the Person.Contact table in AdventureWorks. The XML schema and data for the DataSet is written to a file named ContactDataset.xml. Next, the solution creates a DataSet and reads in schema and data from the XML file ContactDataSet.xml. Finally, the contents of the DataSet are written to the console.

The C# code in Program.cs in the project SaveLoadDataSetXml is shown in Example 9-1.

Example 9-1. File: Program.cs for SaveLoadDataSetXml solution

using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Xml; using System.Text; namespace SaveLoadDataSetXml { class Program { private const string fileName = @"..\..\..\ContactDataSet.xml"; static void Main(string[] args) { string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT ContactID, FirstName, LastName " + "FROM Person.Contact WHERE ContactID BETWEEN 10 AND 13"; // Fill the DataSet using a DataAdapter DataSet dsSource = new DataSet("ContactDataSet"); SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString); da.TableMappings.Add("Table", ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.