How to Export data from DataTable to Xml in C#

By FoxLearn 7/16/2024 9:33:47 AM   6.49K
Exporting data from a DataTable to XML in a C# Windows Forms application is straightforward.

You can use the WriteXml method of the DataTable class to achieve this.

How to Convert DataTable to XML String in C#

Open your Visual Studio, then create a new Windows Forms Application.

Next, Create 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.

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);
}

How to export 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
            {
                // c# save the DataTable to XML file
                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 export your DataTable to XML with schema in c#, you can modify your code as shown below.

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

In this example, when the button btnExportData is clicked, it uses the WriteXml method of the DataTable class to save the data to an XML file.

Related