class
ReadWriteXmlExample
{
staticvoid Main(string[] args)
{
DemonstrateReadWriteXMLDocumentWithStreamReader();
}
privatestaticvoid DemonstrateReadWriteXMLDocumentWithStreamReader()
{
// type variables defined for type comparison
//
Type i32Type = Type.GetType("System.Int32");
Type sType = Type.GetType("System.String");
// Create a DataSet with one table and two columns.
DataSet OriginalDataSet = newDataSet("dataSet");
OriginalDataSet.Namespace =
"NetFrameWork";
DataTable table = newDataTable("table");
DataColumn idColumn = newDataColumn("id", Type.GetType("System.Int32"));
idColumn.AutoIncrement =
true;
DataColumn itemColumn = newDataColumn("item", Type.GetType("System.String"));
table.Columns.Add(idColumn);
table.Columns.Add(itemColumn);
OriginalDataSet.Tables.Add(table);
// Add ten rows.
DataRow newRow;
for (int i = 0; i < 10; i++)
{
newRow = table.NewRow();
newRow[
"item"] = "item " + i;
table.Rows.Add(newRow);
}
OriginalDataSet.AcceptChanges();
// Print out values of each table in the DataSet
// using the function defined below.
PrintValues(OriginalDataSet,
"Original DataSet");
if ((OriginalDataSet.Tables[0].Columns["id"].DataType) == i32Type)
{
Console.WriteLine("ID column types match!");
}
else
{
Console.WriteLine("ID column types *do not* match!");
}
if ((OriginalDataSet.Tables[0].Columns["item"].DataType) == sType)
{
Console.WriteLine("ITEM column types match!");
}
else
{
Console.WriteLine("ITEM column types *do not* match!");
}
Console.ReadLine();
// Write the schema and data to an XML file.
string xmlFilename = "XmlDocument.xml";
// Use WriteXml to write the document.
OriginalDataSet.WriteXml(xmlFilename);
// Dispose of the original DataSet.
OriginalDataSet.Dispose();
// Create a new DataSet.
DataSet newDataSet = newDataSet("New DataSet");
// Read the XML document into the DataSet.
newDataSet.ReadXml(xmlFilename);
if ((newDataSet.Tables[0].Columns["id"].DataType) == i32Type)
{
Console.WriteLine("ID column types match!");
}
else
{
Console.WriteLine("ID column types *do not* match!");
}
if ((newDataSet.Tables[0].Columns["item"].DataType) == sType)
{
Console.WriteLine("ITEM column types match!");
}
else
{
Console.WriteLine("ITEM column types *do not* match!");
}
Console.ReadLine();
// Print out values of each table in the DataSet
// using the function defined below.
PrintValues(newDataSet,
"New DataSet");
Console.ReadLine();
}
privatestaticvoid PrintValues(DataSet dataSet, string label)
{
Console.WriteLine("\n" + label);
foreach (DataTable table in dataSet.Tables)
{
Console.WriteLine("TableName: " + table.TableName);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write("\tcolumn " + row[column]);
}
Console.WriteLine();
}
}
}
}