ASP.NET

XML Documents and DataSet in ASP.NET

Programmingempire

In this post on XML Documents and DataSet in ASP.NET, I will explain how to create an XML Document from a DataSet and vice versa. Also, I will explain how to display XML data in a data-bound control like GridView.

An Example Demonstrating XML Documents and DataSet

The following example shows how to work with XML in ASP.NET. Therefore, we create a database in SQL Server. Further, we create a table named Items.

Specifying Connection String in web.config

Since we create our DataSet by fetching data from an SQL Server database, we use the ConnectionString property of the database. Therefore, we add the <connectionString> tag to the web.config file to specify a connection string. The following figure shows how to add it in the web.config file of the application.

ConnectionString Property in Web.config File
ConnectionString Property in Web.config File

To clarify further, the properties of a database can be accessed from the Server Explorer available in View menu of Visual Studio. So you can right click on the name of the database, select properties option, and get corresponding properties in the Properties Window. As an illustration, the database table Items is shown below.

Items Table in the Database
Items Table in the Database

So, we create a Web Form having two GridView controls and two Button controls. The following code shows the ASPX page containing these controls.

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="XMLAndDataSets.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="GridView1" runat="server"></asp:GridView>
            <br />
            <asp:Button ID="Button1" runat="server" Text="Create XML Document" OnClick="Button1_Click" />
            </div>
        <hr />
        <div>
            <br />
            <asp:Button ID="Button2" runat="server" Text="Convert XML into DataSet" OnClick="Button2_Click" />
            <br />
            <br />
            <asp:GridView ID="GridView2" runat="server"></asp:GridView>
            </div>
    </form>
</body>
</html>

At first, we create a method Connect() that creates a connection to the database. After that, we create a method BindAndDisplay() that binds the first GridView control to the database data. Further, call this method in the Page_Load event handler so that, the web page displays GridView with data when the page is loaded.

Also, the Button1_Click event handler creates an XML file with the name items.xml when the first button is clicked.

WebForm1.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace XMLAndDataSets
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection c1;
        SqlDataAdapter da;
        DataSet ds;
        protected void Page_Load(object sender, EventArgs e)
        {
            BindAndDisplay();
        }
        public void Connect()
        {
            c1 = new SqlConnection(ConfigurationManager.ConnectionStrings["conn1"].ToString());
            c1.Open();
        }
        public void BindAndDisplay()
        {
            Connect();
            da = new SqlDataAdapter("select * from Items", c1);
            ds = new DataSet("ItemRecords");
            da.Fill(ds, "Items");
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            string path = Server.MapPath("XMLFiles");
            string filepath = path + @"items.xml";
            ds.WriteXml(filepath);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            DataSet ds1 = new DataSet();
            string path1 = Server.MapPath(@"");
            string filepath1 = path1 + @"XMLFile1.xml";
            ds1.ReadXml(filepath1);
            GridView2.DataSource = ds1;
            GridView2.DataBind();
        }
    }
}

Output

Synchronizing XML Documents and DataSet in ASP.NET
Synchronizing XML Documents and DataSet in ASP.NET

As shown below, the WriteXML() method of the DataSet class generates the following XML file.

Generated File – items.xml

<?xml version="1.0" standalone="yes"?>
<ItemRecords>
  <Items>
    <item_id>1</item_id>
    <item_name>Watch                                                                                               </item_name>
    <price>2999</price>
    <quantity>8</quantity>
  </Items>
  <Items>
    <item_id>2</item_id>
    <item_name>Smart Phone                                                                                         </item_name>
    <price>12000</price>
    <quantity>4</quantity>
  </Items>
  <Items>
    <item_id>3</item_id>
    <item_name>Power Bank                                                                                          </item_name>
    <price>799</price>
    <quantity>9</quantity>
  </Items>
  <Items>
    <item_id>4</item_id>
    <item_name>Webcam                                                                                              </item_name>
    <price>1300</price>
    <quantity>12</quantity>
  </Items>
  <Items>
    <item_id>5</item_id>
    <item_name>Temperature Sensor                                                                                  </item_name>
    <price>80</price>
    <quantity>50</quantity>
  </Items>
  <Items>
    <item_id>6</item_id>
    <item_name>Fitness Band                                                                                        </item_name>
    <price>455</price>
    <quantity>6</quantity>
  </Items>
  <Items>
    <item_id>7</item_id>
    <item_name>Headphone                                                                                           </item_name>
    <price>1599</price>
    <quantity>3</quantity>
  </Items>
  <Items>
    <item_id>8</item_id>
    <item_name>Pen Drive                                                                                           </item_name>
    <price>499</price>
    <quantity>15</quantity>
  </Items>
  <Items>
    <item_id>9</item_id>
    <item_name>USB Charger                                                                                         </item_name>
    <price>130</price>
    <quantity>20</quantity>
  </Items>
  <Items>
    <item_id>10</item_id>
    <item_name>USB Torch                                                                                           </item_name>
    <price>100</price>
    <quantity>10</quantity>
  </Items>
</ItemRecords>

Converting XML File into DataSet

For the purpose of transforming an XML file into DataSet, we create an XML file. Therefore, we select Add New Item option from the Project menu in Visual Studio and select the XML File option from there.

After that, we create the XML file that includes the Persons data which will form the DataSet.

<?xml version="1.0" encoding="utf-8" ?>
<Persons>
	<Person>
		<pid>1</pid>
		<pname>A</pname>
		<age>12</age>
	</Person>
	<Person>
		<pid>2</pid>
		<pname>B</pname>
		<age>30</age>
	</Person>
	<Person>
		<pid>3</pid>
		<pname>C</pname>
		<age>23</age>
	</Person>
	<Person>
		<pid>4</pid>
		<pname>D</pname>
		<age>44</age>
	</Person>
	<Person>
		<pid>5</pid>
		<pname>E</pname>
		<age>21</age>
	</Person>
	<Person>
		<pid>6</pid>
		<pname>F</pname>
		<age>27</age>
	</Person>
</Persons>

As shown below, clicking on the second button calls the ReadXML() method of the DataSet. Once, this method is called, we get a DataSet object. Finally, we bind the second GridView control using that DataSet object.

Converting XML to DataSet
Converting XML to DataSet

To summarize, XML Documents and DataSet in ASP.NET work interchangeably in ASP.NET. What’s more it very easy to do so with built-in methods of the DataSet class. Therefore, we can bind XML data to a web control by creating a DataSet object from the XML file.


Further Reading

Parameter and ParameterCollection in ADO.NET

Database Manipulation Using DataGrid

Example of Button and Link Button Control in ASP.NET

Example of Chart Control in ASP.NET

Creating a DataTable from a DataReader in ASP.NET

Deleting a Record using DataGrid Control in ASP.NET

Edit a Record Using DataGrid Control in ASP.NET

Insert a Record Using ItemCommand Event in DataGrid

CRUD Operations with DataGrid in ASP.NET

Creating Columns in a DataGrid Control

XML Documents and DataSet in ASP.NET

Code Render Block in ASP.NET

ASP.NET Core Features and Advantages

Display Images Using DataList Control

Adding Images Using Image Control

Creating a Group of Radio Buttons Using RadioButtonList Control

Example of Button Control in ASP.NET

Using MD5 Hash Algorithm

ItemDataBound Event in DataList

More Features of DataList in ASP.NET

A Simple Example of Using a DataList Control in ASP.NET

Properties and Methods of DataList Control in ASP.NET

ASP.NET Practice Exercise

Exploring DataList Control in ASP.NET

Custom Validator Control in ASP.NET

Validation Summary Control in ASP.NET

Validation Controls Examples – RequiredFieldValidator, CompareValidator, and RangeValidator

An Example of Data Binding with RadioButtonList Control

Binding Data to Web Control in ADO.NET

Examples of AdRotator Control in ASP.NET

Examples of Validation Controls in ASP.NET

Overview of MVC architecture in ASP.NET

programmingempire

You may also like...