Convert Xml node list to Data table


XmlDocument xmldoc = new XmlDocument();
FileStream fs = new FileStream(Application.StartupPath + “\\Response.xml”,FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
fs.Close();
XmlNodeList xmlnode;
xmlnode = xmldoc.GetElementsByTagName(comboBox1.Text.Trim());

//ComboBox1.Text means Xml node Name  Here
if (xmlnode.Count > 0)
{
//DataSet ds = new DataSet();
//ds.ReadXml(Application.StartupPath + “\\Response.xml”);
DataTable dt = ConvertXmlNodeListToDataTable(xmlnode);

//ds.ReadXml(
if (dt != null && dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
}

//—-Method for convert xmlnode list to data table
public DataTable ConvertXmlNodeListToDataTable(XmlNodeList xnl)
{
DataTable dt = new DataTable();
int TempColumn = 0;

foreach (XmlNode node in xnl.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 < xnl.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < ColumnsCount; j++)
{
dr[j] = xnl.Item(i).ChildNodes[j].InnerText;
}
dt.Rows.Add(dr);
}
return dt;
}

}

Advertisements

One Response to Convert Xml node list to Data table

  1. Kumaresh says:

    This code does not iterate the nested nodes/all child nodes. It iterates only the outer nodes. What’s the fix to iterate all the child nodes as well?

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

%d bloggers like this: