Thursday, January 31, 2008

Write XML file using DataTable in C#

We can read data from and write data to an xml file using a DataTable object in C# or Visual Basic. What we need to do is to define a DataTable structure and then use that structure to read and write xml file.

In this article I'll show you how to write data to an xml file, but the read process will be shown in the next post. So, let's get the ball rolling!

Okay, the only namespace we need to import is System.Data. This namespace contains DataTable class.

using System.Data;

Declare a DataTable object:

DataTable dt;

Define DataTable structure:

dt = new DataTable("MyTempTable");
dt.Columns.Add("FirstName", System.Type.GetType("System.String"));
dt.Columns.Add("LastName", Type.GetType("System.String"));
dt.Columns.Add("Address", Type.GetType("System.String"));

Declare a DataRow:

DataRow dr;

Create a new DataRow object:

dr = new DataRow();

Create a record to be inserted in the xml file:

dr["FirstName"] = "Joe";
dr["LastName"] = "Somebody";
dr["Address"] = "Somewhere in the world!";

Now add this row to the DataTable:

dt.Rows.Add(dr);

You can add multiple rows in the datatable just like the procedure above. The next step is to simply write the contents or records in an xml file.
And you can write this by simply using the following line of code:

dt.WriteXml("datafilename.xml");

You can write many complex procedures by using this simple tip.
I hope this helps. I'll also write the next post about reading data back into DataTable from XML file. So, stay tuned! :)

1 comment:

De Mello Anthony said...

Doas
"dt.WriteXml("datafilename.xml");" works also with .Net framework 1.1?
I don't think so...Is it true or not?
How can I write an xml file with the content of a datatable using .Net 1.1???
Thanks.