Delete nodes in XML file?

I have an xml file and you want to delete some nodes:

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

I want to delete Name nodes because later I want to create new nodes.

Here is the code 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 
+4
source share
2 answers

Part of the problem is that XML is not valid.

Naming Elements and Attributes

Element names cannot contain spaces.

Assuming valid XML element names, i.e.: 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") 
+3
source

Try RemoveChild instead of RemoveNode.

0
source

Source: https://habr.com/ru/post/1483326/


All Articles