DinDan DinDan - 20 days ago 5
C# Question

How to create DataTable from xml file with types in c#

I have this code that create a xml file from DataTable:

DataTable dt = new DataTable();
dt.TableName = "sdf";
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(int));
dt.Rows.Add(1,2);
dt.Rows.Add(3,4);
dt.WriteXml(@"d:\test123.xml");


In another program I need to read the xml file and to create DataTable/DataSet with integer columns.

dt.ReadXml(@"d:\test123.xml");


This code generate a DataTable with string columns.

How can I define the types of the columns in the DataTable?

Answer

You can create the columns before read xml:

var dt = new DataTable {TableName = "sdf"};
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(int));
dt.ReadXml(@"d:\test123.xml");
Comments