xml - 删除 XML 文件中的节点?

标签 xml vb.net

我有 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/

相关文章:

ruby - 使用 Ruby 和正则表达式就地更改 XML 数据

python - 检查标签是否为空

java - Spring 4 - Autowiring 问题 : org. springframework.beans.factory.UnsatisfiedDependencyException:没有合格的 bean 类型

mysql - 如何查看从 VB.net 代码传递给 SQL 的查询

vb.net - 如何通过反射对对象的可为空属性调用 HasValue?

mysql - Visual Basic 2005 + MySQL

vb.net - 从日期减去天数

javascript - 如何使用 JQuery 展平 XML 树?

java - 尽管 Activity 存在于 AndroidManifest.xml 中,但该 Activity 却不在其中

javascript - 为什么无法从代码隐藏 (vb.net) 中读取 HTML 表中的行?