Monday, June 22, 2009

How to remove nodes from xml.

suppose the xml in XmlFile6.xml is like this

<?xml version="1.0"?>
<items>
<item>
<title>wewewe</title>
<itemid>regdoc</itemid>
<summary>fvdfv</summary>
<body>vf</body>
<image>default.jpg</image>
<author>dddd</author>
<date>2009-02-02 14:26:00.0</date>
</item>
<item>
<title>ww</title>
<itemid>regdoc</itemid>
<summary>fvdfv</summary>
<body>vf</body>
<image>default.jpg</image>
<author>dddd</author>
<date>2009-02-02 14:26:00.0</date>
</item>
</items>


string fileName = Server.MapPath("XMLFile6.xml");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(fileName);
string ddlSelected = "ww";
//suppose ur dropdown'selected value is
//also i suppose that u match the title with thdrodown's selected values.
XmlNode oldChild = xDoc.SelectSingleNode("items/item[title = '"+ ddlSelected +"']");
xDoc.DocumentElement.RemoveChild(oldChild);
//see result here for one node remove
string afterRemove = xDoc.OuterXml;
// The above code will work for only one node which has title as ww
//If u want to do it for multiple nodes then..
ddlSelected = "ww1";
XmlNodeList oldChilds = xDoc.SelectNodes("items/item[title = '" + ddlSelected + "']");
foreach (XmlNode xNode in oldChilds)
{
xDoc.DocumentElement.RemoveChild(xNode);
xDoc.Save(fileName);
}
//see result here for multiple node remove
afterRemove = xDoc.OuterXml;

//Now to add new node to this xml
XmlNode xItem = xDoc.CreateElement("item");
XmlNode xTitle = xDoc.CreateElement("title");
xTitle.InnerText = "kavs";
XmlNode xItemid = xDoc.CreateElement("itemid");
xItemid.InnerText = "itemid";
XmlNode xSummary = xDoc.CreateElement("summary");
xSummary.InnerText = "summary";
//and so on for author and date
xItem.AppendChild(xTitle);
xItem.AppendChild(xItemid);
xItem.AppendChild(xSummary);
xDoc.DocumentElement.LastChild.AppendChild(xItem);

5 comments:

  1. xDoc.DocumentElement.RemoveChild(oldChild);

    iam getting object reference not set to an instance of an object error in the above line ,,pls help me how to resolve it...

    ReplyDelete
  2. Hi ,
    At present I’m developing a registration form in which, when we click on the save button. It will get save in a xml file.
    The details in the xml file should be displayed in the datagrid in separate window form. There are also three buttons. Edit, new and delete.
    On clicking on edit button, the selected rows detail in gridview should display in the registration form. I don’t know how to do this.

    By selecting a row, when we click on delete button , it should delete that particular record from the xml file. This also I’m not getting……….. please help me………………………………..

    ReplyDelete
  3. i didn't get any error when doing this exam but noe record is added to my xml file why..plz reply me soon ....

    ReplyDelete
  4. deepsap_007
    ateeta
    hiii




    i want to delete msg plzzz help me

    ReplyDelete