It’s really easy to write a System.Data.DataTable to an XML file, and you can later Read the XML file back into a DataTable.
First, you need to give the DataTable a name (very important otherwise save table to xml would fail without a tablename), then you want to write the datatable schema to a xml file first. You should then write the data itself into another XML file. So when you’re ready to read the XML file back into a datatable, just load the table schema xml file first, then load the data xml file.
in the following example, I first use traditional ADO.NET to populate some data into table booklist,
then I gave the table name “booklist”, without the tablename, when you writeXML you will get an exception.
Then I use “WriteXmlSchema” function to write the schema of the datatable to a file, then I use WriteXml function to write the actual data to another file.
To Load, I first create a new datatable, then use ReadXmlSchema to read the schema file first to set the data table structure, then read the data by using ReadXml function.
//first populate the DataTable booklist //write the table definition & data into XML file. string filename_data = @"c:\\data.xml"; string filename_schema = @"c:\\schema.xml"; this.booklist.TableName = "booklist"; this.booklist.WriteXml(filename_data); this.booklist.WriteXmlSchema(filename_schema); //read the XML files and populate into a new data table this.booklist = new DataTable(); string filename_data = @"c:\\data.xml"; string filename_schema = @"c:\\schema.xml"; this.booklist.ReadXmlSchema(filename_schema); this.booklist.ReadXml(filename_data);