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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
   <asp:GridView ID="GridView1" runat="server"></asp:GridView>
   </div>
   </form>
</body>
</html>

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

    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("Category.xml"));

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

    GridView1.DataSource = ConvertXmlNodeListToDataTable(elemList);
    GridView1.DataBind();

  }

  public static 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;

  }

}

<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
    <Category>
        <MainCategory ID="1">XML</MainCategory>
        <SubCategory>Basic</SubCategory>
        <Description>List of XML articles.</Description>
        <Active>Yes</Active>
    </Category>
    <Category>
        <MainCategory ID="2">XML1</MainCategory>
        <SubCategory>Basic1</SubCategory>
        <Description>List of XML articles1.</Description>
        <Active>Yes</Active>
    </Category>
</CategoryList>

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

Post a Comment (0)
Previous Post Next Post