Windows Forms: How to Export data from DataTable to Xml in C#

This post shows you How to Export data from DataTable to Xml in C# Windows Forms Application.

Creating a simple UI allows you to load data from customer table in the Northwind database to the DataGridView. When clicking the export button, it allows you to convert datatable to xml file.

How to Convert DataTable to XML String in C#

c# export datatable to xml

After you finish adding bindingsource to the DataGridView, you should see Form_Load as follows.

private void frmExportDataTableToXml_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'appData.Customers' table. You can move, or remove it, as needed.
    this.customersTableAdapter.Fill(this.appData.Customers);
}

DataTable to XML document C#

Adding a click evet handler to the Export button allows you to export data from DataTable to Xml file.

private void btnExportData_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "XML files|*.xml" })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                this.appData.Customers.WriteXml(sfd.FileName);
                MessageBox.Show("You have successfully exported the file.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

If you want to write C# DataTable to XML with schema, you can modify your code as shown below.

this.appData.Customers.WriteXmlSchema(sfd.FileName);

 

Related