Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing nodes from an XmlDocument

The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:

The node to be removed is not a child of this node.

Does anyone know the proper way to do this?

public void DeleteProject (string projectName)
{
    string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];

    XmlDocument configDoc = new XmlDocument();

    configDoc.Load(ccConfigPath);

    XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");

    for (int i = 0; i < projectNodes.Count; i++)
    {
        if (projectNodes[i].Attributes["name"] != null)
        {
            if (projectName == projectNodes[i].Attributes["name"].InnerText)
            {                                                
                configDoc.RemoveChild(projectNodes[i]);
                configDoc.Save(ccConfigPath);
            }
        }
    }
}

UPDATE

Fixed. I did two things:

XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");

Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.

The actual fix was:

project.ParentNode.RemoveChild(project);

Thanks Pat and Chuck for this suggestion.

like image 625
FlySwat Avatar asked Aug 21 '08 17:08

FlySwat


People also ask

How do you delete a node in XML?

Remove a Text Node xml is loaded into xmlDoc. Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.

What is node in XML document?

Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.

What is the difference between XmlNode and XmlElement?

XmlElement is just one kind of XmlNode. Others are XmlAttribute, XmlText etc. An Element is part of the formal definition of a well-formed XML document, whereas a node is defined as part of the Document Object Model for processing XML documents.

What are leaf nodes in XML?

A leaf node is one that has no children so you can simply perform a check if it has children. There are various ways of doing this depending on how you're loading the XML document. For example, you can use the HasChildNodes property.


2 Answers

Instead of

configDoc.RemoveChild(projectNodes[i]); 

try

projectNodes[i].parentNode.RemoveChild(projectNodes[i]); 
like image 117
Pat Avatar answered Oct 08 '22 04:10

Pat


try

configDoc.DocumentElement.RemoveChild(projectNodes[i]);
like image 30
Jason Avatar answered Oct 08 '22 03:10

Jason