是否删除XML文件中的节点?
我有xml文件,想删除一些节点:是否删除XML文件中的节点?,xml,vb.net,Xml,Vb.net,我有xml文件,想删除一些节点: <group> <First group> </First group> <Second group> <Name> </Name> <Name> </Name> <Name> </Name> </Second group> </group> 请尝试Rem
<group>
<First group>
</First group>
<Second group>
<Name>
</Name>
<Name>
</Name>
<Name>
</Name>
</Second group>
</group>
请尝试RemoveChild而不是RemoveNode 部分问题在于XML无效 元素名称不能包含空格 假设XML元素名有效,即:First\u group,Second\u group,下面的代码将从Second\u 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到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")
我收到错误“/group/Second group/Name”包含无效的令牌。谢谢,这对我有效。我将
node.RemoveAll()更改为node.ParentNode.RemoveChild(node)`,因为它保留了节点标题名称,但删除了其中的内容。
Dim doc As XDocument = XDocument.Load("c:\temp\node.xml")
doc.Root.Element("Second_group").Elements("Name").Remove()
doc.Save("c:\temp\node.xml")