Wilicious
Wilicious

Reputation: 15

How do i delete a certain element from XmlDocument?

I can't seem to figure this out. I want to delete line nr 3 from this XML with code.

1 <Storage>
2  <ID1 Name="123" Producer="123" EANnr="123" />
3  <ID2 Name="xxx" Producer="xxx" EANnr="xxx" />
4 </Storage>

This is how I add the line to XML:

public string DBAddToXML()
        {
            XmlNode Storage = storageData.CreateElement("Storage");
            storageData.AppendChild(Storage);

            XmlElement iDAttribute = storageData.CreateElement("ID" + scannedItemId.ToString());         
            iDAttribute.SetAttribute("Name", scannedItemName.ToString());
            iDAttribute.SetAttribute("Producer", scannedItemProducer.ToString());
            iDAttribute.SetAttribute("EANnr", scannedItemEANnr.ToString());
            Storage.AppendChild(iDAttribute);
            
            storageData.Save(STORAGE_DATA_FILE_NAME);
            
            return storageData.InnerXml;
        }

I use this because it's the only thing I found that could add the lines without overwriting anything. If I tried to add a Node, it just didn't add anything, or it replaced everything. But this solution works for me. Except I dont know how to search for the specific line and delete it. The plan was to search for the ID number, which is the name of the element.

This function is only run once. It's to create the file, that's why there no FIle.Load, i have another function for that, but it's identical minus the XmlNode Storage part.

Upvotes: 0

Views: 50

Answers (1)

R. Max
R. Max

Reputation: 36

First you will have to load your document

var doc = new XmlDocument();
doc.LoadXml(storageXmlData);

Then select your element you want to delete

var node = doc.SelectSingleNode("/Storage/ID2");

I recommend you to go through the 'xpath' documentation to know what selector to use. I also recommend you to use an attribut like the name on your element to identify the element and go for a generic type of element.

To finish, you can delete your element from the parent element

if(node != null)
{
    node.ParentNode.RemoveChild(node);
}

Upvotes: 2

Related Questions