Wednesday, February 06, 2008

Read data from XML File using DataTable in C#

Reading data from an xml file with the help of DataTable in C# is very easy. You just need to use one method of DataTable called ReadXML. Here is this article I'll show you how to complete this task of reading xml data into a DataTable.

Before reading xml data into a DataTable you need to make sure that the table structure is consistent with the structure of the xml. The good idea would be to first write the xml file using this same table structure in this DataTable. You can write xml using DataTable and the detail is given in the follwing post:

Write XML file using DataTable in C#

Import follwing namespace:
using System.Data;

We need a DataTable object:

DataTable dt;

This DataTable requires a structure compatible with the xml file structure. We can make sure this compatibility with the help of xml schema as well, but in this article I'll not explain how can we use xml schema to make sure that the structure is same. However, in some next post I'll definitly explain that as well.

Here is the table 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"));

Now, read the xml file into this data table.

dt.ReadXml("filename");

Now, you can process data in the dt as a normal DataTable.

No comments: