Removing nodes from an XmlDocument

2019-01-04 03:12发布

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.

6条回答
太酷不给撩
2楼-- · 2019-01-04 03:39

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

查看更多
Emotional °昔
3楼-- · 2019-01-04 03:47

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();
查看更多
smile是对你的礼貌
4楼-- · 2019-01-04 03:51

Instead of

configDoc.RemoveChild(projectNodes[i]);

try

projectNodes[i].parentNode.RemoveChild(projectNodes[i]);
查看更多
闹够了就滚
5楼-- · 2019-01-04 03:53

try

configDoc.DocumentElement.RemoveChild(projectNodes[i]);
查看更多
祖国的老花朵
6楼-- · 2019-01-04 03:58

Is it possible that the project nodes aren't child nodes, but grandchildren or lower? GetElementsByTagName will give you elements from anywhere in the child element tree, IIRC.

查看更多
做个烂人
7楼-- · 2019-01-04 03:58

It would be handy to see a sample of the XML file you're processing but my guess would be that you have something like this

<Root>
 <Blah>
   <project>...</project>
 </Blah>
</Root>

The error message seems to be because you're trying to remove <project> from the grandparent rather than the direct parent of the project node

查看更多
登录 后发表回答