vb.net 删除 XML 文件中的节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16811041/
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-09-17 13:47:00  来源:igfitidea点击:

Remove nodes in an XML file?

xmlvb.net

提问by Chelovek

I have xml file and want to remove some nodes:

我有 xml 文件并想删除一些节点:

<group>
  <First group>
  </First group>
  <Second group>
    <Name>
    </Name>
    <Name>
    </Name>
    <Name>
    </Name>
  </Second group>
</group>

I want to remove nodes Name, because later I want to create new nodes.

我想删除节点Name,因为稍后我想创建新节点。

Here is the code what I have what I have:

这是我所拥有的代码:

Dim doc As New XmlDocument()
Dim nodes As XmlNodeList
doc.Load("doc.xml")
nodes = doc.SelectNodes("/group")
Dim node As XmlNode

For Each node In nodes
  node = doc.SelectSingleNode("/group/Second group/Name")
  If node IsNot Nothing Then
    node.ParentNode.RemoveNode(node)
    doc.Save("doc.xml")
  End If
Next

采纳答案by maxedev

Part of the problem is the XML is not valid.

部分问题是 XML 无效。

Naming Elements and Attributes

命名元素和属性

Element names cannot contain spaces.

元素名称不能包含空格。

Assuming valid XML element names ie: First_group, Second_group, the following code removes all children from Second_group

假设有效的 XML 元素名称即:First_group、Second_group,以下代码从 Second_group 中删除所有子项

Dim doc As New XmlDocument()
Dim nodes As XmlNodeList
doc.Load("c:\temp\node.xml")
nodes = doc.SelectNodes("/group/Second_group")

For Each node As XmlNode In nodes
    If node IsNot Nothing Then
        node.RemoveAll()
          doc.Save("c:\temp\node.xml")
    End If
Next

Or LINQ to XML:

或 LINQ to XML:

Dim doc As XDocument = XDocument.Load("c:\temp\node.xml")
doc.Root.Element("Second_group").Elements("Name").Remove()
doc.Save("c:\temp\node.xml")

回答by Crwydryn

Try RemoveChild instead of RemoveNode.

尝试 RemoveChild 而不是 RemoveNode。