2013-05-29 86 views
4

我有XML文件,并想消除一些节点:删除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 

回答

3

问题的一部分是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所有儿童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") 
+1

谢谢,这对我有用。我将'node.RemoveAll()改成了'node.ParentNode.RemoveChild(node)',因为它是留下节点标题Name,但是删除了里面的内容。 – Chelovek

0

尝试removeChild之代替的removeNode。

+0

我收到错误“/组/第二组/名称“有一个无效的标记。 – Chelovek