Navigator: Home - Retrieve - A sample of operating XML data in ASP.NET 2.0(C#)

A sample of operating XML data in ASP.NET 2.0(C#)

A sample of operating XML data in ASP.NET 2.0(C#)

Microsoft .NET introduces a new suite of XML APIs built on industry standards such as DOM, XPath, XSD, and XSLT. The .NET Framework XML classes also offer convenience, better performance, and a more familiar programming model, tightly coupled with the new .NET data access APIs—ADO .NET. XmlWriter, XmlReader, and XmlNavigator classes and classes that derive from them, including XMLTextReader and XMLTextWriter, encapsulate a number of functionalities that previously had to be accomplished manually. This tutorial will show you a sample of how to operate XML in ASP.NET and C#.

Download the Full Working Version of this Project written with Visual Studio.NET C# 2005 Here!

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

The System.Xml namespace contains the XmlDocument Class. We can use this class to operate xml file. For instance, add, modify, delete and clear data to XML file.

At first, import the namespace of System.Xml

using System.Xml;
using System.Data;

Add four buttons to web page. They are Add, modify, Delete and Clear.
Add 2 functions: One is loadXmlData, and the other is FindXmlData.

// insert data to xml file
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
//Create a new node
XmlElement newelement = xmldoc.CreateElement("poems");
XmlElement xmlAuthor = xmldoc.CreateElement("author");
XmlElement xmlTitle = xmldoc.CreateElement("title");
XmlElement xmlContent = xmldoc.CreateElement("content");

xmlAuthor.InnerText = this.TextBox1.Text.Trim();
xmlTitle.InnerText = this.TextBox2.Text.Trim();
xmlContent.InnerText = this.TextBox3.Text.Trim();

newelement.AppendChild(xmlAuthor);
newelement.AppendChild(xmlTitle);
newelement.AppendChild(xmlContent);

xmldoc.DocumentElement.AppendChild(newelement);

//xmlDoc.DocumentElement.InsertAfter(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//xmlDoc.DocumentElement.InsertBefore(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//save
xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
}

// modify one xml data based on selecteditem
protected void Button2_Click(object sender, EventArgs e)
{
if (selectIndex == -1)
{
this.RegisterClientScriptBlock("alertmessage", "<script>alert('please select one modify data item.')</script>");
}
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);

xmlnode["author"].InnerText = this.TextBox1.Text.Trim();
xmlnode["title"].InnerText = this.TextBox2.Text.Trim();
xmlnode["content"].InnerText = this.TextBox3.Text.Trim();

xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
}
}

// Delete one xml data base on selecteditem
protected void Button3_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);
xmlnode.ParentNode.RemoveChild(xmlnode);
xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
this.TextBox1.Text = "";
this.TextBox2.Text = "";
this.TextBox3.Text = "";
}

// clear textbox value
protected void Button4_Click(object sender, EventArgs e)
{
this.TextBox1.Text = "";
this.TextBox2.Text = "";
this.TextBox3.Text = "";
}

// load xml data from xml file
private void loadXmlData()
{
DataSet myDs = new DataSet();
myDs.ReadXml(Server.MapPath(@"App_Data\smallfools.xml"));

if (myDs.Tables.Count > 0)
{
this.GridView1.DataSource = myDs;
this.GridView1.DataBind();
}
}

//select one data and fill data to textbox
private void FindXmlData(int selectedIndex)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNodeList xmlnodelist = xmldoc.DocumentElement.ChildNodes;
XmlNode xmlnode = xmlnodelist.Item(selectedIndex);
this.TextBox1.Text = xmlnode["author"].InnerText;
this.TextBox2.Text = xmlnode["title"].InnerText;
this.TextBox3.Text = xmlnode["content"].InnerText;
}
//get selectedItem index
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
selectIndex = this.GridView1.SelectedIndex;
FindXmlData(selectIndex);
}

The front page of Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Default</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="height: 401px">
<legend>Operate Xml</legend>
author:&nbsp;<asp:TextBox ID="TextBox1" runat="server" Width="231px"></asp:TextBox><br />
title: &nbsp; &nbsp;&nbsp;<asp:TextBox ID="TextBox2" runat="server" Width="231px"></asp:TextBox><br />
content:<asp:TextBox ID="TextBox3" runat="server" Width="231px"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="modify" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Delete" />
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="Clear" /><br /><br />

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="428px" AutoGenerateColumns="False">
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:CommandField CancelText="Cancel" DeleteText="Delete" EditText="Modify" InsertText="Insert" NewText="New" SelectText="Select" ShowSelectButton="True" UpdateText="Update" />
<asp:BoundField DataField="author" HeaderText="Author" />
<asp:BoundField DataField="title" HeaderText="Title" />
<asp:BoundField DataField="content" HeaderText="Content" />
</Columns>
<RowStyle BackColor="#E3EAEB" />
<EditRowStyle BackColor="#7C6F57" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</fieldset>
</div>
</form>
</body>
</html>


The code behind the front page

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
internal int selectIndex
{
get
{
if (this.Session["Page_selectIndex"] == null)
return -1;
return Int32.Parse(this.Session["Page_selectIndex"].ToString());
}
set
{
this.Session["Page_selectIndex"] = value;
}
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
loadXmlData();
}
}

/// <summary>
/// load xml data
/// </summary>
private void loadXmlData()
{
DataSet myDs = new DataSet();
myDs.ReadXml(Server.MapPath(@"App_Data\smallfools.xml"));

if (myDs.Tables.Count > 0)
{
this.GridView1.DataSource = myDs;
this.GridView1.DataBind();
}
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
selectIndex = this.GridView1.SelectedIndex;
FindXmlData(selectIndex);
}

/// <summary>
/// search xml data base in dataGridView1.CurrentRow.Index
/// </summary>
/// <param name="selectIndex"></param>
private void FindXmlData(int selectedIndex)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNodeList xmlnodelist = xmldoc.DocumentElement.ChildNodes;
XmlNode xmlnode = xmlnodelist.Item(selectedIndex);
this.TextBox1.Text = xmlnode["author"].InnerText;
this.TextBox2.Text = xmlnode["title"].InnerText;
this.TextBox3.Text = xmlnode["content"].InnerText;
}

protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
//Create a new node
XmlElement newelement = xmldoc.CreateElement("poems");
XmlElement xmlAuthor = xmldoc.CreateElement("author");
XmlElement xmlTitle = xmldoc.CreateElement("title");
XmlElement xmlContent = xmldoc.CreateElement("content");

xmlAuthor.InnerText = this.TextBox1.Text.Trim();
xmlTitle.InnerText = this.TextBox2.Text.Trim();
xmlContent.InnerText = this.TextBox3.Text.Trim();

newelement.AppendChild(xmlAuthor);
newelement.AppendChild(xmlTitle);
newelement.AppendChild(xmlContent);

xmldoc.DocumentElement.AppendChild(newelement);

//xmlDoc.DocumentElement.InsertAfter(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//xmlDoc.DocumentElement.InsertBefore(newElement,xmlDoc.DocumentElement.ChildNodes.Item(0));
//save
xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
}

protected void Button2_Click(object sender, EventArgs e)
{
if (selectIndex == -1)
{
this.RegisterClientScriptBlock("alertmessage", "<script>alert('please select one modify data item.')</script>");
}
else
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);

xmlnode["author"].InnerText = this.TextBox1.Text.Trim();
xmlnode["title"].InnerText = this.TextBox2.Text.Trim();
xmlnode["content"].InnerText = this.TextBox3.Text.Trim();

xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
}
}

protected void Button3_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath(@"App_Data\smallfools.xml"));
XmlNode xmlnode = xmldoc.DocumentElement.ChildNodes.Item(selectIndex);
xmlnode.ParentNode.RemoveChild(xmlnode);
xmldoc.Save(Server.MapPath(@"App_Data\smallfools.xml"));

loadXmlData();
this.TextBox1.Text = "";
this.TextBox2.Text = "";
this.TextBox3.Text = "";
}
protected void Button4_Click(object sender, EventArgs e)
{
this.TextBox1.Text = "";
this.TextBox2.Text = "";
this.TextBox3.Text = "";
}
}


Download the Full Working Version of this Project written with Visual Studio.NET C# 2005 Here!

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!
411asp.net123aspxDotNetFreaksServer Intellect