Thursday, March 22, 2012

How to update the XML file in asp.net

Title:How to read and update XML in asp.net using c#

Description: As per asp.net we have specific number of data source controls.Among these i have used XML data source control for my application.So now i would like to describe and explain about CRUD operations on XML file.As initial we have to get the data source path and read the data from the file .

Example:In the below example we have create a instance for XML document and load  from the specified path.Then i will get the all sales order id's using node list and iterate through the complete document.Mean while we are getting the sales Order customer title and update the name as per data
using System;
using System.Collections.Generic;
using System.Data;
using System.XML;

private void ReadAndUpdateXml_Click(object sender, EventArgs e)
{
XmlDocument newXmldoc= new XmlDocument();
newXmldoc.Load(Server.MapPath("~/XMLFiles/salesOrder.xml"));
XmlNodeList nodeList = newXmldoc.SelectNodes("//Orders/OrderId");
int i = 1;
foreach (XmlNode updatedNode in nodeList)
{
XmlNode updatedNode = newXmldoc.SelectSingleNode("//Orders/OrderId[position()='" +i + "']");
string salesOrderId = updatedNode.SelectSingleNode("ID").InnerText;
updatedNode.SelectSingleNode("Title").InnerText ="Specified Customer";
XmlNode UpdateTitle = newXmldoc.CreateNode(XmlNodeType.Element, "MetaTitle", null);
UpdateTitle.InnerText = "Desired Customer";
updateNode.AppendChild(UpdateTitle);
i++;
}
newXmldoc.Save(Server.MapPath("~/XMLFiles/salesOrder.xml"));
}
Post a Comment

Bel