We have the following XML data in an 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>John Smith</Name>
- <Marks>200</Marks>
- </STUDENT>
- <STUDENT>
- <StudentID>2</StudentID>
- <Name>Mark Johnson</Name>
- <Marks>300</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="ConvertXMLtoDatatable.aspx.cs" Inherits="ConvertDatatabletoXMLString.ConvertXMLtoDatatable" %>
-
- <!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;
- usingSystem.Collections.Generic;
- usingSystem.Data;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.UI;
- usingSystem.Web.UI.WebControls;
- namespaceConvertDatatabletoXMLString
- {
- public partial class ConvertXMLtoDatatable: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!Page.IsPostBack)
- {
- ConvertXMLtoDataSet();
- }
- }
- protected void ConvertXMLtoDataSet()
- {
- DataSetobjDataSet;
- stringstrFileName = 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;
- }
- }
- }
- }
When we run the page we get the following output.
We have successfully converted XML to Dataset in C# and bound a Gridview with the dataset.