Convert XML to Dataset in C#

We have the following XML data in an XML file named ‘Student.xml’. The XML is present in the root folder of our application.

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <STUDENTS>  
  3.     <STUDENT>  
  4.         <StudentID>1</StudentID>  
  5.         <Name>John Smith</Name>  
  6.         <Marks>200</Marks>  
  7.     </STUDENT>  
  8.     <STUDENT>  
  9.         <StudentID>2</StudentID>  
  10.         <Name>Mark Johnson</Name>  
  11.         <Marks>300</Marks>  
  12.     </STUDENT>  
  13. </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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ConvertXMLtoDatatable.aspx.cs" Inherits="ConvertDatatabletoXMLString.ConvertXMLtoDatatable" %>  
  2.   
  3.     <!DOCTYPE html>  
  4.   
  5.     <html xmlns="http://www.w3.org/1999/xhtml">  
  6.   
  7.     <head runat="server">  
  8.         <title></title>  
  9.     </head>  
  10.   
  11.     <body>  
  12.         <form id="form1" runat="server">  
  13.             <div>  
  14.                 <asp:GridView ID="Grddata" runat="server"></asp:GridView>  
  15.             </div>  
  16.         </form>  
  17.     </body>  
  18.   
  19.     </html>  
In the Code behind write the following code,
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Data;  
  4. usingSystem.Linq;  
  5. usingSystem.Web;  
  6. usingSystem.Web.UI;  
  7. usingSystem.Web.UI.WebControls;  
  8. namespaceConvertDatatabletoXMLString  
  9. {  
  10.     public partial class ConvertXMLtoDatatable: System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.             if (!Page.IsPostBack)  
  15.             {  
  16.                 ConvertXMLtoDataSet();  
  17.             }  
  18.         }  
  19.         protected void ConvertXMLtoDataSet()  
  20.         {  
  21.             DataSetobjDataSet;  
  22.             stringstrFileName = string.Empty;  
  23.             try  
  24.             {  
  25.                 strFileName = Server.MapPath("Student.xml");  
  26.                 objDataSet = new DataSet();  
  27.                 objDataSet.ReadXml(strFileName);  
  28.                 Grddata.DataSource = objDataSet;  
  29.                 Grddata.DataBind();  
  30.             }  
  31.             catch (Exception Ex)  
  32.             {  
  33.                 throw Ex;  
  34.             }  
  35.             finally  
  36.             {  
  37.                 objDataSet = null;  
  38.                 strFileName = string.Empty;  
  39.             }  
  40.         }  
  41.     }  
  42. }  
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.

 


Next Recommended Reading Convert XML/ JSON File To C# Class