Click here to Skip to main content
15,399,688 members
Articles / Web Development / ASP.NET
Tip/Trick
Posted 26 Jul 2013

Tagged as

Stats

31.5K views
638 downloads
9 bookmarked

Reading XML Data into a DataTable Using ASP.NET

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
26 Jul 2013CPOL
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

XML
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
C#
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:

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

Output

Default view -

Image 1

Selected Dropdown Value View -

Image 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mannava Siva Aditya
Web Developer
India India
I am a 29 year old software Web Developer from Hyderabad, India. I have been working since approximately age 25. Where as in IT Development industry since 27. I am Microsoft Certified Technology Specialist.

I have taught myself in development, beginning with Microsoft's technologies ASP.NET, Approximately 3 years ago, I was given an opportunity to work as a freelance in the tech field. Now I am working as a web developer where my roles make me purely in web based technology solutions which manage and control access to applications and patient information stored in legacy systems, client-server applications.

I too had an opportunity to train some IT professionals with technical skills in development area. Which became my passion.

I have worked on various .NET framework versions(2.0 , 3.5, 4.0) and have been learning every new technology being introduced. Currently, I am looking forward to working in R & D in .Net to create distributed, reusable applications.

Comments and Discussions

 
-- There are no messages in this forum --