Remove Node From XML file!


Well-known member
Feb 2, 2013
Programming Experience
I am trying to remove a specific node from a XML file called "CustomersInfo" and the node is "Customer"
I have a listbox on my form that has all the customer names in it..when the user highlights the name in the listbox that they want to remove I would like to remove this customer from the XML is the code I have so far

   string path = Application.StartupPath + "[URL="file://\\CustomerInfo\\CustomerInfo.xml"]\\CustomerInfo\\CustomerInfo.xml[/URL]";
            XmlDocument doc = new XmlDocument();
            XmlTextReader xmlReader = new XmlTextReader(path);
            XmlNodeList nodes = doc.SelectNodes("/Customer");
            for (int i = nodes.Count - 1; i >= 0; i++)

this doesnt seem correct to me....this will not delete the node where the user hightlight's the customer they want to remove...also I am getting a error "process cannot access file because it is being used by another process"

any help would be appreciated

This seems strange, "/Customer" refers to root node, and there can only be one root node, so why the loop? Maybe you have a sample xml you can post?
That you can't write to the file that is currently used by your reader is natural, close the file reader before you overwrite the file. If you don't have a specific use for the reader object you can remove it and specify a string path instead, XmlDocument will then handle open/read/closing the file.

I would rather use Linq to Xml for this, here is an example that removes descendant Customer nodes from a document:
            var x = XDocument.Load(path);
thank you for your help!

here is the XML document
<BusinessName>Inked Apparel</BusinessName>
<ContactAddress>Address Here</ContactAddress>
<BusinessName>Todds Landscapes</BusinessName>

hopefully you can help me get this sorted out.

Building on the previous Linq example, this select the Customer descendants where its BusinessName node has a specific value, and removes them:
x.Descendants("Customer").Where(n => n.Element("BusinessName").Value == "Inked Apparel").Remove();
the problem I see with this is ...I won't know the customer wanting to be removed......I have some code I wrote that does the job.....took me awhile but I finally got it.

 string path = Application.StartupPath + "[URL="file://\\CustomerInfo\\CustomerInfo.xml"]\\CustomerInfo\\CustomerInfo.xml[/URL]";
            XmlDocument doc = new XmlDocument();
            string customer = lstCustomers.SelectedItem.ToString();
            foreach (XmlNode xNode in doc.SelectNodes("Customers/Customer"))
                if (xNode.SelectSingleNode("BusinessName").InnerText == customer) xNode.ParentNode.RemoveChild(xNode);

not sure if this is the best way to do it...but it does what I need it to do......

Thanks for your help JohnH

Top Bottom