Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Reading XML Data into a DataTable Using ASP.NET

0.00/5 (No votes)
26 Jul 2013 1  
Reading XML data into a DataTable.

Introduction

Sometimes, we need to read huge amounts of data from XML and need to be displayed on the page. Here we can do this in many ways but in this example I will explain how to read XML data via DataTable in ASP.NET. You just need to use one method of DataTable called ReadXML. This tip will explain how to use the XML structure with the same.

Background

Before reading the XML Data (Country.xml) on DataTable we need to make sure that the table structure is consistent with xml. For processing this first create the XML data file & then create the ReadXML.aspx application for opening XML.

Here we are taking a Dropdown list & Grid View – As the dropdown is used for filtering the state. And grid view is used for presenting the data read from the country.xml file using datatable and the code is been mentioned in below:

Using the code

ReadXML.aspx 
<p>
<asp:Label ID="lblState" runat="server" Text="Filter by state:" />
<asp:DropDownList ID="ddlState" runat="server" 
         AutoPostBack="true" AppendDataBoundItems="True"
         OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
    <asp:ListItem Selected="True" Value="All States">- All States -</asp:ListItem>
</asp:DropDownList>
</p>
<asp:GridView ID="grvForm" runat="server" 
        ClientIDMode="Static" CellPadding="4" 
        ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:Label ID="lblErr" runat="server" />
ReadXML.aspx.cs
using System;
using System.Web.UI.WebControls;
using System.Data; 
using System.Collections.Generic;

public partial class ReadXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GenerateData("All States");
        }
    }
    private void GenerateData(string p)
    {
        string path = Server.MapPath("~/Country.xml");
        DataTable dt = new DataTable("rootStateIndividual");
        try
        {
            //Add Columns in datatable - Column names must match XML File nodes 
            dt.Columns.Add("State", typeof(System.String));
            dt.Columns.Add("Capital", typeof(System.String));
            dt.Columns.Add("Description", typeof(System.String));
            // Reading the XML file and display data in the gridview         
            dt.ReadXml(path);
            if (!String.IsNullOrEmpty(p) && p != "All States")
            {
                // Getting up Theme where condition
                List<datatState> ar = new List<datatState>();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["State"].ToString() == p)
                        {
                            ar.Add(new datatState() { State = dt.Rows[i]["State"].ToString(), 
                              Capital = dt.Rows[i]["Capital"].ToString(), 
                              Description = dt.Rows[i]["Description"].ToString() });
                        }
                    }
                }
                dt.Clear();
                DataRow dr;
                foreach (var item in ar)
                {
                    dr = dt.NewRow();
                    dr["State"] = item.State;
                    dr["Capital"] = item.Capital;
                    dr["Description"] = item.Description;
                    dt.Rows.Add(dr);
                }
                dt.Columns["State"].ColumnName = "State";
                dt.Columns["Capital"].ColumnName = "Capital";
                dt.Columns["Description"].ColumnName = "Description";
                grvForm.DataSource = dt;
                grvForm.DataBind();
            }
            else
            {
                DataTable dtState = new DataTable("rootStateIndividual");
                //Add Columns in datatable - Column names must match XML File nodes 
                dtState.Columns.Add("State", typeof(System.String));
                // Reading the XML file and display data in the dropdown list box
                dtState.ReadXml(path);
                // Create a DataView on DataTable & pass the column name
                // to check for duplicates as array into table method of DataView.
                DataView dView = new DataView(dtState);
                string[] arrColumns = { "State" };
                ddlState.DataSource = dView.ToTable(true, arrColumns);
                ddlState.DataValueField = "State";
                ddlState.DataBind();
                dt.Columns["State"].ColumnName = "State";
                dt.Columns["Capital"].ColumnName = "Capital";
                dt.Columns["Description"].ColumnName = "Description";
                grvForm.DataSource = dt;
                grvForm.DataBind();
            }
            foreach (GridViewRow row in grvForm.Rows)
            {
                row.Cells[0].CssClass = "col1";
                row.Cells[1].CssClass = "col2";
                row.Cells[2].CssClass = "col3";
            }
        }
        catch (Exception ex)
        {
            lblErr.Text = ex.ToString();
        }
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        GenerateData(ddlState.SelectedValue);
    }
}
public class datatState
{
    public string State;
    public string Capital;
    public string Description;
}   
Country.xml
file consists of:

<Country>
  <rootStateIndividual>
    <State></State>
    <Capital></Capital>
    <Description></Description>
  </rootStateIndividual>
</Country>

Output

Default view -

Selected Dropdown Value View -

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here