I am currently upgrading my XML book that I wrote a decade ago to .NET 4.5 and you will be seeing many more articles on XML and .NET. A few days ago, I wrote How to Load XML File into a DataGridView Control and now here is the reverse method.
This article shows how to write DataSet contents to an XML file. The DataSet class contains methods to write a XML file from a DataSet object and fill the data to the file.
The WriteXml Method
The WriteXml method writes the current data (the schema and data) of a DataSet object to an XML file. This is an overloaded method. By using this method, you can write data to a file, stream, TextWriter, or XmlWriter.
The following code snippet writes a DataSet contents to a XML file using the WriteXml method:
- DataSet ds = CreateDynamicDataSet();
- ds.WriteXml(@"C:\Books\Students.xml");
Sample
Create a Windows Forms or WPF application and add a Button control to the Form/Window. Write the following code snippet for the button control click event handler.
The CreateDynamicDataSet method creates a DataSet object in-memory. If you already have data coming from a database, getting filled in a DataSet, you won't need this method. All you need to do is call the WriteXml method of your DataSet and pass the full path of the XML file.
This example creates a DataSet, fills the data for the DataSet, and writes the data to an XML file.
- private void WriteXmlButton_Click(object sender, EventArgs e)
- {
- DataSet ds = CreateDynamicDataSet();
- ds.WriteXml(@"C:\Books\Students.xml");
- }
-
- private DataSet CreateDynamicDataSet()
- {
-
- DataSet ds = new DataSet("DS");
- ds.Namespace = "StdNamespace";
- DataTable stdTable = new DataTable("Student");
- DataColumn col1 = new DataColumn("Name");
- DataColumn col2 = new DataColumn("Address");
- stdTable.Columns.Add(col1);
- stdTable.Columns.Add(col2);
- ds.Tables.Add(stdTable);
-
-
- DataRow newRow; newRow = stdTable.NewRow();
- newRow["Name"] = "Mahesh Chand";
- newRow["Address"] = "Meadowlake Dr, Dtown";
- stdTable.Rows.Add(newRow);
- newRow = stdTable.NewRow();
-
- newRow["Name"] = "Mike Gold";
- newRow["Address"] = "NewYork";
- stdTable.Rows.Add(newRow);
- newRow = stdTable.NewRow();
- newRow["Name"] = "Mike Gold";
- newRow["Address"] = "New York";
-
- stdTable.Rows.Add(newRow);
- ds.AcceptChanges();
- return ds;
-
- }
You wouldn't believe how much the WriteXml method can do for you. If you see the output Students.xml file, it generates a standard XML file that looks like the following.
- <DS xmlns="StdNamespace">
- <Student>
- <Name>Mahesh Chand</Name>
- <Address>Meadowlake Dr, Dtown</Address>
- </Student>
- <Student>
- <Name>Mike Gold</Name>
- <Address>NewYork</Address>
- </Student>
- <Student>
- <Name>Mike Gold</Name>
- <Address>New York</Address>
- </Student>
- </DS>