Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Tuesday, February 22, 2011

Update Existing Xml file

//Xml File

?xml version="1.0" encoding="utf-8"?>
CategoryList>
Category ID="01">
MainCategory>XML /MainCategory>
Description>This is a list my XML articles. /Description>
Active>true /Active>
/Category>
Category ID="02">
MainCategory>Asp.net /MainCategory>
Description>Subahsh /Description>
Active>True /Active>
/Category>
/CategoryList>


//aspx.cs

if (!IsPostBack)
{
XmlDocument xml = new XmlDocument();
string s = Server.MapPath("XMLfILE.xml");
string list = "/CategoryList/Category";
xml.Load(s);
XmlNodeList xn = xml.SelectNodes(list);
foreach (XmlNode eleSourceNode in xn)
{
string ID = eleSourceNode.Attributes["ID"].Value;
string author1 = eleSourceNode["MainCategory"].InnerText;
DropDownList1.Items.Add(new ListItem(author1, ID));
}


}

//DropDown SelectIndexChange

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='"+DropDownList1.SelectedValue+"' ]");

TextBox2.Text = nodeList[0].ChildNodes[0].InnerText;
TextBox3.Text= nodeList[0].ChildNodes[1].InnerText;
TextBox4.Text = nodeList[0].ChildNodes[2].InnerText;

}

//Update Xml File

protected void btnUpdateXml_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("XMLfILE.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes("/CategoryList/Category[@ID='" + DropDownList1.SelectedValue + "' ]");

// update MainCategory
nodeList[0].ChildNodes[0].InnerText = TextBox2.Text.Trim();
// update Description
nodeList[0].ChildNodes[1].InnerText = TextBox3.Text.Trim();
// update Active
nodeList[0].ChildNodes[2].InnerText = TextBox4.Text.Trim();

// Don't forget to save the file
xmlDoc.Save(Server.MapPath("XMLfILE.xml"));
}

No comments:

Post a Comment