Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DataTable to XML file and viceversa

I am having a problem with reading an XML file onto a DataTable. Initially, I am writing a Datatable to an XML file and saving it. Now, when I want to read the XML file back to the DataTable, it's not happening.

The following code is for writing the file:

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) 
{
    if (myDT_For_DGV.Rows.Count != 0)
    {
        saveFileDialog1.ShowDialog();
        saveFileDialog1.FileName = "checkOutFile.xml";
        myDT_For_DGV.TableName = "CheckOutsAndIns";
        myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
    }
    else
    {
        MessageBox.Show("Please add licences to DataGridView, you havent added any licences as of now", "Alert");
    }
}

And for reading the file:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    //write code to open file
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        //myFile = openFileDialog1.FileName;
        System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();

        xmlStream.Position = 0;

        myDT_For_DGV.ReadXml(openFileDialog1.FileName);
        //MessageBox.Show(openFileDialog1.FileName);
    }
}
like image 250
Yash Avatar asked Jun 28 '10 21:06

Yash


2 Answers

It might be easier to just work with the higher-level DataSet, like this:

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();

dataSet.Tables.Add(dataTable);
// Save to disk
dataSet.WriteXml(@"C:\MyDataset.xml");

// Read from disk
dataSet.ReadXml(@"C:\MyDataset.xml");
like image 95
Robert Seder Avatar answered Nov 14 '22 18:11

Robert Seder


I fixed it, The Problem is, the tablename was assigned while saving but not while reading. So assign the table name globally, which will let it read and write without any problem.

so the code will be,

myDT_For_DGV.TableName = "CheckOutsAndIns";

if (openFileDialog1.ShowDialog() == DialogResult.OK) 
       {              
              myDT_For_DGV.ReadXml(@openFileDialog1.FileName);
            //MessageBox.Show(openFileDialog1.FileName);

        }

//TO WRITE TO XML
if (myDT_For_DGV.Rows.Count != 0)
        {
            saveFileDialog1.ShowDialog();
            saveFileDialog1.FileName = "checkOutFile.xml";
            myDT_For_DGV.WriteXml(saveFileDialog1.FileName, true);
        }
like image 45
Yash Avatar answered Nov 14 '22 17:11

Yash