create, read and write xml file through c# asp .net
//default.cs file
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Xml_Insert();
Xml_update();
}
}
public void Xml_Insert()
{
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = xmlDoc.CreateElement("CategoryList");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);
XmlElement parentNode = xmlDoc.CreateElement("Category");
parentNode.SetAttribute("ID", "01");
xmlDoc.DocumentElement.PrependChild(parentNode);
XmlElement mainNode = xmlDoc.CreateElement("MainCategory");
XmlElement descNode = xmlDoc.CreateElement("Description");
XmlElement activeNode = xmlDoc.CreateElement("Active");
XmlText categoryText = xmlDoc.CreateTextNode("XML");
XmlText descText = xmlDoc.CreateTextNode("This is a list my XML articles.");
XmlText activeText = xmlDoc.CreateTextNode("true");
parentNode.AppendChild(mainNode);
parentNode.AppendChild(descNode);
parentNode.AppendChild(activeNode);
mainNode.AppendChild(categoryText);
descNode.AppendChild(descText);
activeNode.AppendChild(activeText);
xmlDoc.Save(Server.MapPath("categories.xml"));
Response.Write("XML file created");
}
public void Xml_update()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("categories.xml"));
XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='01']");
nodeList[0].ChildNodes[0].InnerText = "Deepak";
nodeList[0].ChildNodes[1].InnerText = "Pooja";
nodeList[0].ChildNodes[2].InnerText = "Ashok";
xmlDoc.Save(Server.MapPath("categories.xml"));
Response.Write("XML File updated!");
}
}
//default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
// xml file
="1.0"="utf-8"
<CategoryList>
<Category ID="01">
<MainCategory>Deepak</MainCategory>
<Description>Pooja</Description>
<Active>Ashok</Active>
</Category>
</CategoryList>