Thursday 14 June 2012

Read Xml Data in asp.net

XML Data

01<!--?xml version="1.0" standalone="yes"?-->
02<details>
03  <employee>
04    <firstname>Amit</firstname>
05    <lastname>Jain</lastname>
06    <location>Mumbai</location>
07  </employee>
08  <employee>
09    <firstname>User</firstname>
10    <lastname>1</lastname>
11    <location>Delhi</location>
12  </employee>
13  <employee>
14    <firstname>User</firstname>
15    <lastname>2</lastname>
16    <location>Bangalore</location>
17  </employee>
18</details>

Write below mentioned code in Click event of Read Button.

C# CODE
01protected void btnReadXmlFile_Click(object sender, EventArgs e)
02    {
03        string filePath = Server.MapPath("~/Employees.xml");
04        //Employee Must match with the element name in
05        //your file
06        DataTable dt = new DataTable("Employee");
07 
08        //Add Columns in datatable
09        //Column names must match XML File nodes
10        dt.Columns.Add("firstname", typeof(System.String));
11        dt.Columns.Add("lastname", typeof(System.String));
12        dt.Columns.Add("location", typeof(System.String));
13 
14        //Read XML File And Display Data in GridView
15        dt.ReadXml(filePath);
16        GridView1.DataSource = dt;
17        GridView1.DataBind();
18    }

VB.NET CODE
01Protected Sub btnReadXmlFile_Click(sender As Object, e As EventArgs)
02 Dim filePath As String = Server.MapPath("~/Employees.xml")
03 'Employee Must match with the element name in
04 'your file
05 Dim dt As New DataTable("Employee")
06 
07 'Add Columns in datatable
08 'Column names must match XML File nodes
09 dt.Columns.Add("firstname", GetType(System.String))
10 dt.Columns.Add("lastname", GetType(System.String))
11 dt.Columns.Add("location", GetType(System.String))
12 
13 'Read XML File And Display Data in GridView
14 dt.ReadXml(filePath)
15 GridView1.DataSource = dt
16 GridView1.DataBind()
17End Sub