Read and write XML to-and-from a dataset
This article, obtained from CodeNotes, illustrates the use of the DataSet's WriteXML() and ReadXML() methods to read and write XML to a DataSet.
=== READ XML DATA TO DATASET =======
using System;
using System.Data;
using System.Data.SQL;
using System.IO;
public class ReadXML
{
public static void Main()
{
// Instantiate a new DataSet object
DataSet ds = new DataSet();
// Instantiate a new FileStream object.
FileStream fstream =
new FileStream
("myXmlData.xml",FileMode.Open,FileAccess.Read);
// Apply the ReadXml method to read the file
ds.ReadXml(fstream);
// Get a DataTable object
DataTable dtable = ds.Tables[0];
// Loop to display values for each row
foreach (DataRow drow in dtable.Rows)
// Do Business Logic
;
fstream.Close();
}
}
=== WRITE DATASET DATA TO XML =====
private void WriteXMLExample(DataSet ds) {
if (ds == null) { return; }
// You need to create a file name to write the XML into.
string fname = "XMLDocument.xml";
// Instantiate FileStream object used to write XML.
System.IO.FileStream fstream = new System.IO.FileStream
(fname, System.IO.FileMode.Create);
// Instantiate a XmlTextWriter
System.Xml.XmlTextWriter myXmlWriter =
new System.Xml.XmlTextWriter(fstream,
System.Text.Encoding.Unicode);
// Write to the file using WriteXML()
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();
}
Last Updated:Thursday, September 02, 2010By:alfero#
with your OpenID.
If you do not know what OpenID is,