How to Import Data from XML to GridView

How to Import Data from XML to GridView

In this tutorial i will let you know how to import data from xml to gridview.In this first we have to upload the xml file , after upload the file will be worked as a data source for gridview and it will be shown in gridview.

Design For XML to GridView:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <style type="text/css">
            width: 900px;
    <form id="form1" runat="server">
        <table align="center" class="style1">
                    Choose Your XML File:-<asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                    <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC"
                        BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal"
                        <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                        <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                        <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                        <SortedAscendingCellStyle BackColor="#F7F7F7" />
                        <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
                        <SortedDescendingCellStyle BackColor="#E5E5E5" />
                        <SortedDescendingHeaderStyle BackColor="#242121" />

Code For XML to GridView:-

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void Button1_Click(object sender, EventArgs e)

        if (FileUpload1.HasFile)
            string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string filextension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            if (filextension == ".xml")
                string pathname;
                pathname = Server.MapPath("xmlfiles/" + filename);
                DataSet ds = new DataSet();
                GridView1.DataSource = ds;
                Response.Write("Not a valid XML file");



Read data from XML