C# 如何从 XmlNodeList 中删除 XmlNode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/875136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:03:04  来源:igfitidea点击:

How to remove an XmlNode from XmlNodeList

c#xml

提问by

I need to remove an XmlNode based on a condition. How to do it?

我需要根据条件删除 XmlNode。怎么做?

foreach (XmlNode drawNode in nodeList)
{
       //Based on a condition
       drawNode.RemoveAll();  //need to remove the entire node                      

}

回答by Daniel Wedlund

You can not easily use iterators (foreach-statement) to delete your nodes. As I see it you can do the following:

你不能轻易地使用迭代器(foreach-statement)来删除你的节点。正如我所见,您可以执行以下操作:

1) In your foreach-loop, save a list of all elements that should be removed. Then you loop through just those elements and remove them.

1) 在您的 foreach 循环中,保存应删除的所有元素的列表。然后你只遍历这些元素并删除它们。

2) Use an ordinary for-loop and keep track of which is the next element to visit after you have deleted one item.

2) 使用普通的 for 循环并跟踪删除一个项目后要访问的下一个元素。

Edit: When using a for-loop do it the way Fredrik suggests, looping backwards.

编辑:当使用 for 循环时,按照 Fredrik 建议的方式进行,向后循环。

回答by Keltex

If you're trying to remove a node from the XML DOM, this isn't the correct way. Because an XMLNodeListis just a list of nodes. Rather you want to remove the node from the parent node. Like this:

如果您尝试从 XML DOM 中删除节点,这不是正确的方法。因为 anXMLNodeList只是一个节点列表。相反,您希望从父节点中删除该节点。像这样:

XmlNode parentNode = // some value
XmlNode drawNode = // some value
parentNode.ParentNode.RemoveChild(drawNode);

回答by Fredrik M?rk

This should do the trick for you:

这应该对你有用:

for (int i = nodeList.Count - 1; i >= 0; i--)
{
    nodeList[i].ParentNode.RemoveChild(nodeList[i]);
}

If you loop using a regular for-loop, and loop over it "backwards" you can remove items as you go.

如果您使用常规 for 循环进行循环,并“向后”循环,您可以随时删除项目。

Update: here is a full example, including loading an xml file, locating nodes, deleting them and saving the file:

更新:这是一个完整的示例,包括加载 xml 文件、定位节点、删除它们并保存文件:

XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("some-xpath-query");
for (int i = nodes.Count - 1; i >= 0; i--)
{
    nodes[i].ParentNode.RemoveChild(nodes[i]);
}
doc.Save(fileName);

回答by Rudy Schockaert

Isn't the following a little simpler:

下面是不是更简单一点:

XmlDocument doc = new XmlDocument(); 
doc.Load(fileName); 
XmlNodeList nodes = doc.SelectNodes("some-xpath-query"); 
while (nodes.FirstChild != null) {     
    nodes.RemoveChild(nodes.FirstChild); 
} 
doc.Save(fileName); 

回答by Milind Morey

    XmlNodeList xnodeContact = xmldocContact.GetElementsByTagName("contact");
          foreach (ListViewItem item in listViewContacts.Items)
            {
                if (item.Checked)
                {
                    if (item.Index >= 0)
                        xnodeContact[0].ParentNode.RemoveChild(xnodeContact[0]);
                        listViewContacts.Items.Remove(item);
                    }
                }
            }
            xmldocContact.Save(appdataPath + "\WhatAppcontactList.xml");
            Invalidate();

回答by vapcguy

Seems to me you're trying to just remove an entire XML Element...

在我看来,您只是想删除整个 XML 元素...

If this is your XML...

如果这是您的 XML...

<Xml1>
  <body>
    <Book>
      <Title name="Tom Sawyer" />
      <Author value="Mark Twain" />
    </Book>
    <Book>
      <Title name="A Tale of Two Cities" />
      <Author value="Charles Dickens" />
    </Book>
  </body>
</Xml1>

If you wanted to delete a book, you need to grab the first <Book>node. You can do that with:

如果要删除一本书,则需要抓取第一个<Book>节点。你可以这样做:

XmlDocument doc = new XmlDocument();
doc.Load(fileName);

XmlNodeList nodes = doc.GetElementsByTagName("body");
XmlNode bodyNode = nodes[0];
XmlNode firstBook = bodyNode.ChildNodes[0];

Once you have the "first book" node, you can delete that from the body node using:

拥有“第一本书”节点后,您可以使用以下命令从正文节点中删除它:

bodyNode.RemoveChild(firstBook);

This will automatically affect/update the XML Document variable, so docwill now only have:

这将自动影响/更新 XML 文档变量,因此doc现在只有:

<Xml1>
  <body>
    <Book>
      <Title name="A Tale of Two Cities" />
      <Author value="Charles Dickens" />
    </Book>
  </body>
</Xml1>

If you want to grab and delete the whole body, you should be able to do:

如果你想抓取和删除整个body,你应该能够做到:

XmlNodeList xml1 = doc.GetElementsByTagName("Xml1");
XmlNode xmlNode = xml[0];
xmlNode.RemoveChild(bodyNode);

And the docvariable will be updated to no longer contain the bodyelement, and can then be resaved to the file system:

并且该doc变量将被更新为不再包含该body元素,然后可以重新保存到文件系统:

doc.Save(fileName);

Where fileNameis the full path to the XML Document on your computer.

fileName计算机上 XML 文档的完整路径在哪里。

Best of all, we aren't using doc.SelectNodes(), so we don't need to worry about using an XMLNamespaceManager.

最重要的是,我们没有使用doc.SelectNodes(),因此我们无需担心使用XMLNamespaceManager.