XML in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.XPath;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
XmlTextWriter writer = new XmlTextWriter("G:\\new4.xml",
System.Text.Encoding.Default);
writer.WriteStartDocument();
//creating the name of the main node
writer.WriteStartElement("menu");
writer.WriteStartElement("RECORD");
writer.WriteStartElement("First");
writer.WriteString("Mahesh");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteStartElement("RECORD");
writer.WriteStartElement("First");
writer.WriteString("nikhil");
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();

}

protected void Button2_Click(object sender, EventArgs e)
{
// Create xml dom
XmlDocument XMLDom = new XmlDocument();
//load your xml file
XMLDom.Load(@"g:/new4.xml");
XmlNode root = XMLDom.DocumentElement;
XmlNode childNode = XMLDom.CreateNode(XmlNodeType.Element,
"RECORD", "");
XmlElement newbook = XMLDom.CreateElement("First");
newbook.InnerText = "saurabh";
//XmlElement newbook2 = XMLDom.CreateElement("Second");
//newbook2.InnerText = "mittal";
childNode.AppendChild(newbook);
root.AppendChild(childNode);
XMLDom.Save("g:/new4.xml");

}

protected void Button3_Click(object sender, EventArgs e)
{
// Select childnode where you want to modify data. The
following step "PNode" is parent node and "Node1" is the one which you
want to update the data
// Create xml dom
// Create xml dom
XmlDocument XMLDom = new XmlDocument();
//load your xml file
XMLDom.Load(@"g:/new4.xml");

XmlNodeList newXMLNodes = XMLDom.SelectNodes("/menu/RECORD/First");
foreach (XmlNode newXMLNode in newXMLNodes)
//Updating data where "Node1" is "sree" with "kambham"
if (newXMLNode.InnerText == "Mahesh")
//to modify
newXMLNode.InnerText = "meena";
//to delete
// newXMLNode.ParentNode.RemoveChild(newXMLNode);
XMLDom.Save("g:/new4.xml");
XMLDom = null;
//The above step updates xml file where ever it finds
"sree" with "kambham"
}
}
}
Ebook Download
View all
Learn
View all