Chelovek
Chelovek

Reputation: 159

Remove nodes in an XML file?

I have xml file and want to remove some nodes:

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

I want to remove nodes Name, because later I want to create new nodes.

Here is the code what I have what I have:

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

Upvotes: 4

Views: 17320

Answers (2)

maxedev
maxedev

Reputation: 941

Part of the problem is the XML is not valid.

Naming Elements and Attributes

Element names cannot contain spaces.

Assuming valid XML element names ie: First_group, Second_group, the following code removes all children from 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

Or 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")

Upvotes: 3

Crwydryn
Crwydryn

Reputation: 840

Try RemoveChild instead of RemoveNode.

Upvotes: 0

Related Questions