Convert xml string to DataTable or DataSet in C#

In this post, I will show you how to convert the XML node to DataTable using C#. XML is a very popular format for sharing data between two applications. Sometimes we need to parse the XML to our business objects (in our case data table).

DataSet represents an in-memory cache of data.{alertSuccess}

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="XmlNodeListToDataTable.aspx.cs" Inherits="XmlNodeListToDataTable" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="" >
<head runat="server">
   <title>Untitled Page</title>
   <form id="form1" runat="server">
   <asp:GridView ID="GridView1" runat="server"></asp:GridView>

public partial class XmlNodeListToDataTable: System.Web.UI.Page {
  protected void Page_Load(object sender, EventArgs e) {

    XmlDocument doc = new XmlDocument();

    //Get and display all the book titles.
    XmlElement root = doc.DocumentElement;
    XmlNodeList elemList = root.GetElementsByTagName("Category");

    GridView1.DataSource = ConvertXmlNodeListToDataTable(elemList);


  public static DataTable ConvertXmlNodeListToDataTable(XmlNodeList xnl) {

    DataTable dt = new DataTable();

    int TempColumn = 0;

    foreach(XmlNode node in xnl.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());

      } else {




    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;




    return dt;



<?xml version="1.0" encoding="utf-8"?>
        <MainCategory ID="1">XML</MainCategory>
        <Description>List of XML articles.</Description>
        <MainCategory ID="2">XML1</MainCategory>
        <Description>List of XML articles1.</Description>

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post