Delete A Node Based On It's Attribute

In this blog post, we will delete a node from an xml file based on its specified id attribute. The code below is written in C#

Xml File

<?xml version="1.0" encoding="utf-8"?>
<Document>
  <List id="1"></List>
  <List id="2"></List>
  <List id="3"></List>
  <List id="4"></List>
  <List id="5"></List>
  <List id="6"></List>
  <List id="7"></List>
</Document>

Code Behind:

  // Save the Xml File Path in a variable
   string xmlFilePath = Server.MapPath("~") + "/text.xml";

   // Create an instance of the XmlDocument
   XmlDocument mydoc = new XmlDocument();
   
   // Load the Xml File
   mydoc.Load(xmlFilePath);
   
   // Select Root Element
   XmlNode rootNode = mydoc.SelectSingleNode("Document");

   // Delete Single Node based on specific Attribute
   XmlNode mynode = mydoc.SelectSingleNode("Document/List[@id='1']");
   
   // Delete the Node
   rootNode.RemoveChild(mynode);

   // Save the Xml File Back
   mydoc.Save(xmlFilePath);

Best Regards,

HC

 

 

 

Comments

# re: Delete A Node Based On It's Attribute

Sunday, July 08, 2007 9:34 PM by VMP

Thanks, mate. Just what I was looking for.

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.