Saturday, October 1, 2011

Delete an XML node C#

In this article, I will show you how to remove an XML node by a given ID in C# language.
I have an XML document:

<Products>
      <Product>
            <ID>1</ID>
            <ProductName>Samsung </ProductName>
      </Product>
      <Product>
            <ID>2</ID>
            <ProductName>Sony </ProductName>
      </Product>      
</Products>

Now I want to delete the product that has ID = 2

protected void deleteXMLNode(int ID)
{
      XmlDocument xmlDoc = new XmlDocument();
      xmlDoc.Load(Server.MapPath("XML\\myFile.xml"));
      XmlNode node = xmlDoc.SelectSingleNode("//Product[ID=2]");
      node.ParentNode.RemoveChild(node);
      xmlDoc.Save(Server.MapPath("XML\\myFile.xml"));
}

Hope this helps! :)

1 comments:

Phạm Anh Tuấn said...

love this ;)

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews