Saturday, July 13, 2013

Asp.net Read xml node values and bind data to gridview

SampleXML.xml
----------------
<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SE</Role>
    </Job>
  </user>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SOftware Developer</Role>
    </Job>
  </user>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SE</Role>
    </Job>
  </user>
</users>
Default.aspx
------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="XML_Default8" %>
<!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 id="Head1" runat="server">
<title>Read XML Node values and bind data to gridview</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</form>
</body>
</html>
Default.aspx.cs
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
public partial class XML_Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind Data to Gridview
            GetXMLData();
        }
    }
    // This method is used to get xml node values and bind to gridview
    protected void GetXMLData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("FirstName", typeof(string));
        dt.Columns.Add("LastName", typeof(string));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Role", typeof(string));
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("~/SampleXML.xml"));
        XmlNodeList nodeList = xmldoc.SelectNodes("/users/user");
        foreach (XmlNode node in nodeList)
        {
            DataRow dtrow = dt.NewRow();
            dtrow["FirstName"] = node["FirstName"].InnerText;
            dtrow["LastName"] = node["LastName"].InnerText;
            dtrow["UserName"] = node["UserName"].InnerText;
            dtrow["Role"] = node["Job"]["Role"].InnerText;
            dt.Rows.Add(dtrow);
        }
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
}

0 comments:

Post a Comment