删除XML文件中的节点?

前端之家收集整理的这篇文章主要介绍了删除XML文件中的节点?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有xml文件,想要删除一些节点:

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

我想删除节点名称,因为以后我想创建新节点.

以下是我拥有的代码

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")
@H_502_45@

猜你在找的XML相关文章