我有 xml 文件并想删除一些节点:
<group>
<First group>
</First group>
<Second group>
<Name>
</Name>
<Name>
</Name>
<Name>
</Name>
</Second group>
</group>
我想删除节点 Name
,因为稍后我想创建新节点。
这是我所拥有的代码:
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
最佳答案
部分问题是 XML 无效。
Naming Elements and Attributes
元素名称不能包含空格。
假设有效的 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
或 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")
关于xml - 删除 XML 文件中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16811041/