How to remove an XmlNode from XmlNodeList
我需要根据条件删除XmlNode。 怎么做?
1 2 3 4 5 6 | foreach (XmlNode drawNode in nodeList) { //Based on a condition drawNode.RemoveAll(); //need to remove the entire node } |
这应该为您解决问题:
1 2 3 4 | for (int i = nodeList.Count - 1; i >= 0; i--) { nodeList[i].ParentNode.RemoveChild(nodeList[i]); } |
如果使用常规的for循环,然后"向后"循环,则可以随时删除项目。
更新:这是一个完整的示例,包括加载xml文件,查找节点,删除它们并保存文件:
1 2 3 4 5 6 7 8 | 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); |
如果您试图从XML DOM中删除节点,则这不是正确的方法。因为
1 2 3 | XmlNode parentNode = // some value XmlNode drawNode = // some value parentNode.ParentNode.RemoveChild(drawNode); |
您不能轻易使用迭代器(foreach语句)来删除节点。
如我所见,您可以执行以下操作:
1)在foreach循环中,保存应删除的所有元素的列表。然后,您仅遍历那些元素并将其删除。
2)使用普通的for循环,并在删除一项后跟踪下一个要访问的元素。
编辑:使用for循环时,按照Fredrik建议的方式进行,然后向后循环。
在我看来,您正在尝试仅删除整个XML元素...
如果这是您的XML ...
1 2 3 4 5 6 7 8 9 10 11 12 | <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> |
如果要删除一本书,则需要获取第一个
1 2 3 4 5 6 | XmlDocument doc = new XmlDocument(); doc.Load(fileName); XmlNodeList nodes = doc.GetElementsByTagName("body"); XmlNode bodyNode = nodes[0]; XmlNode firstBook = bodyNode.ChildNodes[0]; |
拥有"第一本书"节点后,可以使用以下方法从正文节点中将其删除:
1 | bodyNode.RemoveChild(firstBook); |
这将自动影响/更新XML Document变量,因此
1 2 3 4 5 6 7 8 | <Xml1> <body> <Book> <Title name="A Tale of Two Cities" /> <Author value="Charles Dickens" /> </Book> </body> </Xml1> |
如果要抓取并删除整个
1 2 3 | XmlNodeList xml1 = doc.GetElementsByTagName("Xml1"); XmlNode xmlNode = xml[0]; xmlNode.RemoveChild(bodyNode); |
并且
1 | doc.Save(fileName); |
其中
最好的是,我们没有使用
以下内容是否简单一些:
1 2 3 4 5 6 7 | 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); |
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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(); |