Convert XMLElement to DataTable

Posted: November 9, 2011 in Code

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)
{
TempColumn++;
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());
}
else
{
dt.Columns.Add(dc);
}
}
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;
else
dr[j] = “”;
}
dt.Rows.Add(dr);
}
return dt;
}

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

<EmployeeDetails>
<Employee>
<ID>1</ID>
<Name>xxx</Name>
</Employee>
<Employee>
<ID>2</ID>
<Name>yyy</Name>
</Employee>
</EmployeeDetails>
 

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s