I have the following XML data in a XML file named ‘Student.xml’. The XML is present in the root folder of our application.
- <?xml version="1.0" encoding="utf-8" ?>
-
- <STUDENTS>
-
- <STUDENT>
-
- <StudentID>1</StudentID>
-
- <Name>soumalya das</Name>
-
- <Marks>300</Marks>
-
- </STUDENT>
-
- <STUDENT>
-
- <StudentID>2</StudentID>
-
- <Name>Paramita basu das</Name>
-
- <Marks>400</Marks>
-
- </STUDENT>
-
- </STUDENTS>
We will display this data in a gridview using C#. Create a web application. Add a webpage. Copy the following code in the aspx page.
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
-
- <title></title>
-
- </head>
-
- <body>
-
- <form id="form1" runat="server">
-
- <div>
-
- <asp:GridView ID="Grddata" runat="server"></asp:GridView>
-
- </div>
-
- </form>
-
- </body>
-
- </html>
In the code behind write the following code:
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace ConvertDatatabletoXMLString
- {
- public partial class ConvertXMLtoDatatable : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- ConvertXMLtoDataSet();
- }
- }
- protected void ConvertXMLtoDataSet()
- {
- DataSet objDataSet;
- string strFileName=string.Empty;
- try
- {
- strFileName = Server.MapPath("Student.xml");
- objDataSet = new DataSet();
- objDataSet.ReadXml(strFileName);
- Grddata.DataSource = objDataSet;
- Grddata.DataBind();
- }
- catch (Exception Ex)
- {
- throw Ex;
- }
- finally
- {
- objDataSet = null;
- strFileName = string.Empty;
- }
- }
- }
- }