开发者

XmlNode.RemoveChild() method does not work as expected

I am trying to remove specific node from xml document by looping through it. Here is what I have tried:

foreach (XmlNode node in doc.ChildNodes) {
    if (node.Name == "EmbeddedResource" && node.Attributes["Include"].Value.Contains(".resx")) {
           node.ParentNode.RemoveChild(node);
     }
}

Nothing happens when this code is executed. No exception is thrown also. I have googled a little and found some solution with SelectSingleNode method but it requires XPath as input parameter and it is too complicated in my opinion, because I already have the node that I want. This is how it looks like (by the way, I couldn't make it work because there开发者_JAVA百科 is something wrong with my XPath):

parentNode.RemoveChild(parentNode.SelectSingleNode("//" + parentNode.Name + "/" + node.Name + "[@Include='" + node.Attributes["Include"].Value + "']"));

Why is this method behaving like this? Is there a way to do this differently?

Thanks is advance


Since you're iterating through doc.ChildNodes, why don't you use doc.RemoveChild(node)?

Also there may be a problem in that you're iterating through a list whilst removing items from that list - I don't know how C# would handle that. You could, for example, store a temporary list of nodes to delete in your original foreach and then iterate through the temporary list to delete the items from the doc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜