Alex Rivera | Logout

Removing nodes from an XmlDocument

Asked 2008-08-21T17:31:27.247
51

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.

Edit
Report

3 Answers

2

try

configDoc.DocumentElement.RemoveChild(projectNodes[i]);
answered 2008-08-21T17:39:43.387
2

Looks like you need to select the parent node of projectNodes[i] before calling RemoveChild.

answered 2008-08-21T17:41:22.090
2

When you get sufficiently annoyed by writing it the long way (for me that was fairly soon) you can use a helper extension method provided below. Yay new technology!

public static class Extensions {
    ...
    public static XmlNode RemoveFromParent(this XmlNode node) {
        return (node == null) ? null : node.ParentNode.RemoveChild(node);
    }
}
...
//some_long_node_expression.parentNode.RemoveChild(some_long_node_expression);
some_long_node_expression.RemoveFromParent();
answered 2012-06-20T09:43:59.937

Your Answer