Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to delete a parent node and everything within the record, but I'm a bit stuck with where to go.

What I have tried:

VB.NET
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Dim contactlist As New XmlDocument()
    contactlist.Load("contactlist.xml")
    Dim contactNode As XmlNode = contactlist.SelectSingleNode("contacts")
    Dim contacts As XmlNodeList = contactNode.SelectNodes("contact")
    For index As Integer = 0 To contacts.Count - 1
        Dim contact As XmlNode = contact(index)
        If txtSearch.Text = contact("name").InnerText Then
            contact.ParentNode.RemoveChild(contact)
        End If
    Next
    contactlist.Save("contactlist2.xml")
End Sub

here is the XML, I want to be able to delete one contact
XML
<Contacts>
  <contact>
    <name>James</name>
    <address>123 Yes street</address>
    <place>Mel</place>
    <phone>12345678</phone>
    <email>123@123.com</email>
  </contact>
  <contact>
    <name>Ken</name>
    <address>123 Yes street</address>
    <place>Mel</place>
    <phone>12345678</phone>
    <email>123@123.com</email>
  </contact>
Posted
Updated 15-Jul-21 23:47pm
v2

This would be easiest with LINQ to XML:
Overview - LINQ to XML | Microsoft Docs[^]
VB.NET
Dim contactList As XDocument = XDocument.Load("contactlist.xml")
Dim nodesToRemove As List(Of XElement) = contactList.Descendants("contact").Where(Function(el) CStr(el.Element("name")) = txtSearch.Text).ToList()
For Each node As XElement In nodesToRemove
    node.Remove()
Next

contactList.Save("contactlist2.xml")
 
Share this answer
 
//using System.Linq;
//using System.Xml.Linq;
XElement x = XElement.Load("contactlist.xml");
var ken = x.Elements("contact").Where(n => n.Element("name").Value == "Ken");
ken.Remove();
x.Save("contactlist.xml");

In VB.NET:
Dim x As XElement = XElement.Load("contactlist.xml")
Dim ken = x.Elements("contact").Where(Function(n) n.Element("name").Value = "Ken")
ken.Remove()
x.Save("contactlist.xml")
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900