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:

  1. DataSet ds = CreateDynamicDataSet();
  2. 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.

  1. private void WriteXmlButton_Click(object sender, EventArgs e)
  2. {
  3. DataSet ds = CreateDynamicDataSet();
  4. ds.WriteXml(@"C:\Books\Students.xml");
  5. }
  6. private DataSet CreateDynamicDataSet()
  7. {
  8. DataSet ds = new DataSet("DS");
  9. ds.Namespace = "StdNamespace";
  10. DataTable stdTable = new DataTable("Student");
  11. DataColumn col1 = new DataColumn("Name");
  12. DataColumn col2 = new DataColumn("Address");
  13. stdTable.Columns.Add(col1);
  14. stdTable.Columns.Add(col2);
  15. ds.Tables.Add(stdTable);
  16. //Add student Data to the table
  17. DataRow newRow; newRow = stdTable.NewRow();
  18. newRow["Name"] = "Mahesh Chand";
  19. newRow["Address"] = "Meadowlake Dr, Dtown";
  20. stdTable.Rows.Add(newRow);
  21. newRow = stdTable.NewRow();
  22. newRow["Name"] = "Mike Gold";
  23. newRow["Address"] = "NewYork";
  24. stdTable.Rows.Add(newRow);
  25. newRow = stdTable.NewRow();
  26. newRow["Name"] = "Mike Gold";
  27. newRow["Address"] = "New York";
  28. stdTable.Rows.Add(newRow);
  29. ds.AcceptChanges();
  30. return ds;
  31. }
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.

  1. <DS xmlns="StdNamespace">
  2. <Student>
  3. <Name>Mahesh Chand</Name>
  4. <Address>Meadowlake Dr, Dtown</Address>
  5. </Student>
  6. <Student>
  7. <Name>Mike Gold</Name>
  8. <Address>NewYork</Address>
  9. </Student>
  10. <Student>
  11. <Name>Mike Gold</Name>
  12. <Address>New York</Address>
  13. </Student>
  14. </DS>