Read XML File Into DataTable In ASP.NET C# VB

In this example i'm explaining how to Read XML File Data Into DataTable In Asp.Net Using C# And VB.NET

I have created a XML File which contains FirstName, LastName and Location sub elements which is shown below.

Read XML File Data Into DataTable C# VB.NET ASP.NET

Element name Employee must be passed while creating object of DataTable.







XML Data

Amit Jain Mumbai User 1 Delhi User 2 Bangalore

Write below mentioned code in Click event of Read Button.

C# CODE
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Employees.xml");
        //Employee Must match with the element name in 
        //your file
        DataTable dt = new DataTable("Employee");
        
        //Add Columns in datatable
        //Column names must match XML File nodes
        dt.Columns.Add("firstname", typeof(System.String));
        dt.Columns.Add("lastname", typeof(System.String));
        dt.Columns.Add("location", typeof(System.String));
        
        //Read XML File And Display Data in GridView
        dt.ReadXml(filePath);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.NET CODE
Protected Sub btnReadXmlFile_Click(sender As Object, e As EventArgs)
 Dim filePath As String = Server.MapPath("~/Employees.xml")
 'Employee Must match with the element name in 
 'your file
 Dim dt As New DataTable("Employee")

 'Add Columns in datatable
 'Column names must match XML File nodes
 dt.Columns.Add("firstname", GetType(System.String))
 dt.Columns.Add("lastname", GetType(System.String))
 dt.Columns.Add("location", GetType(System.String))

 'Read XML File And Display Data in GridView
 dt.ReadXml(filePath)
 GridView1.DataSource = dt
 GridView1.DataBind()
End Sub

If you like this post than join us or share

4 comments:

Markus said...

dataTable.ReadXml() will fail to load as the root 'employee' has 3 levels. Have to use dataSet.ReadXml() and get result from dataSet.Tables[0];


Unknown said...

@bejoy: if you write code as i have mentioned above, it will work without any error


Anonymous said...

How to display information using asp.net


Sanjay Ror said...

very nice code sir thanks a lot..


Find More Articles