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

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", "Contact");
da.FillSchema(dsSource, SchemaType.Source);
da.Fill(dsSource);

// Output the DataSet to the console
Console.WriteLine("---Source DataSet---");
foreach (DataRow row in dsSource.Tables["Contact"].Rows)
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}",
row["ContactID"], row["FirstName"], row["LastName"]);

// Write the XSD schema and data to a file.
FileStream fsOut =
new FileStream(fileName, FileMode.Create, FileAccess.Write);
// Create an XmlTextWriter using the file stream.
XmlTextWriter xtw = new XmlTextWriter(fsOut, Encoding.Unicode);
// Write the XML to the file.
dsSource.WriteXml(xtw, XmlWriteMode.WriteSchema);
xtw.Close();

Console.WriteLine("\nXML file written.");

// Read the XML file into a new DataSet
FileStream fsIn =
new FileStream(fileName, FileMode.Open, FileAccess.Read);
// Create an XmlTextReader using the file stream.
XmlTextReader xtr = new XmlTextReader(fsIn);
DataSet dsDest = new DataSet();
dsDest.ReadXml(xtr, XmlReadMode.ReadSchema);

// Output the DataSet to the console.
Console.WriteLine("\nXML file loaded into DataSet.");
Console.WriteLine("\n---Destination DataSet---");
foreach (DataRow row in dsDest.Tables["Contact"].Rows)
Console.WriteLine("ContactID = {0}\tFirstName = {1}\tLastName = {2}",
row["ContactID"], row["FirstName"], row["LastName"]);

Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

Use the WriteXmlSchema() and ReadXmlSchema() methods of the DataSet and DataTable classes to write and read just XSD schema information.

No comments: