Convert XMLElement to DataTable

Below is the code to convert an XMLElement object containing values to a DataTable. The XMLElement tag names will be the column headings in the DataTable.

public DataTable ConvertXmlElementToDataTable(XmlElement xmlElement, string tagName)
XmlNodeList xmlNodeList = xmlElement.GetElementsByTagName(tagName);

DataTable dt = new DataTable();
int TempColumn = 0;
foreach (XmlNode node in xmlNodeList.Item(0).ChildNodes)
DataColumn dc = new DataColumn(node.Name, System.Type.GetType(“System.String”));
if (dt.Columns.Contains(node.Name))
dt.Columns.Add(dc.ColumnName = dc.ColumnName + TempColumn.ToString());
int ColumnsCount = dt.Columns.Count;
for (int i = 0; i < xmlNodeList.Count; i++)
DataRow dr = dt.NewRow();
for (int j = 0; j < ColumnsCount; j++)
if (xmlNodeList.Item(i).ChildNodes[j] != null)
dr[j] = xmlNodeList.Item(i).ChildNodes[j].InnerText;
dr[j] = “”;
return dt;

The parameters for this method are the actual XMLElement & the outer tag name in the XML. For example considering the below XML,


You will be passing “Employee” as the second parameter for the method. Returned data table will be having columns “ID” & “Name”.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: