ASP.
NET Program to Implement XML
Classes
This example demonstrates how to use XML classes in ASP.NET using C#. It shows how to
create an XML file using XmlTextWriter, read it using XmlDocument, and display the
contents on the web page.
ASPX Page (XmlExample.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="XmlExample.aspx.cs"
Inherits="XmlExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XML Classes Example</title>
</head>
<body>
<form id="form1" runat="server">
<h2>XML Classes Example</h2>
<asp:Button ID="btnCreate" runat="server" Text="Create XML"
OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read XML"
OnClick="btnRead_Click" />
<br /><br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
Code-behind (XmlExample.aspx.cs)
using System;
using System.Xml;
public partial class XmlExample : System.Web.UI.Page
{
string xmlFilePath = @"C:\Temp\Students.xml"; // You can change the path
protected void btnCreate_Click(object sender, EventArgs e)
{
XmlTextWriter writer = new XmlTextWriter(xmlFilePath, null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Students");
writer.WriteStartElement("Student");
writer.WriteElementString("Id", "1");
writer.WriteElementString("Name", "Arun");
writer.WriteElementString("Department", "CSE");
writer.WriteEndElement();
writer.WriteStartElement("Student");
writer.WriteElementString("Id", "2");
writer.WriteElementString("Name", "Divya");
writer.WriteElementString("Department", "ECE");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
lblResult.Text = "XML file created successfully at " + xmlFilePath;
}
protected void btnRead_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
string output = "";
XmlNodeList nodeList = doc.GetElementsByTagName("Student");
foreach (XmlNode node in nodeList)
{
string id = node["Id"].InnerText;
string name = node["Name"].InnerText;
string dept = node["Department"].InnerText;
output += $"ID: {id}, Name: {name}, Department: {dept}<br/>";
}
lblResult.Text = output;
}
}
Explanation
1. When you click 'Create XML', an XML file is created at the specified path with student
details.
2. When you click 'Read XML', the XML file is read using XmlDocument, and the data is
displayed on the web page.
3. You can change the file path as per your environment.
4. Make sure the folder (e.g., C:\Temp) exists and has write permission.