Code to delete an XML attribute VB.NET 2005

arthurh88
arthurh88 used Ask the Experts™
on
<doc>
  <loop1 name="MyLoop1" type="Min" length="20" data="Sample XML File" />
  <loop2 name="MyLoop2" type="Sec" length="50" data="some more data" />
</doc>

what code would I need to delete, say,  the entire loop2 from this XML file?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi arthurh88,

You can use this routine to delete a specific node....

    Public Sub DeleteNode(ByVal FilePath As String, ByVal NodeName As String)
        If MsgBox("Delete node '" & NodeName & "' from " & FilePath & "?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            Dim doc As New System.Xml.XmlDocument
            doc.Load(FilePath)
            Dim nd As System.Xml.XmlNode
            Try
                nd = doc.DocumentElement.GetElementsByTagName(NodeName).Item(0)
            Catch ex As Exception
                MsgBox("Node '" & NodeName & "' could not be found in the file " & FilePath, MsgBoxStyle.Exclamation)
                Exit Sub
            End Try
            doc.DocumentElement.RemoveChild(nd)
            doc.Save(FilePath)
            MsgBox("Node Removed!")
        End If
    End Sub

Cal it like this....

    DeleteNode("C:\test.xml", "loop2")

Regards,

Wayne
Sorry, a bug in the event of the node not being found. This one works better....

    Public Sub DeleteNode(ByVal FilePath As String, ByVal NodeName As String)
        If MsgBox("Delete node '" & NodeName & "' from " & FilePath & "?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            Dim doc As New System.Xml.XmlDocument
            doc.Load(FilePath)
            Dim nd As System.Xml.XmlNode

            nd = doc.DocumentElement.GetElementsByTagName(NodeName).Item(0)
            If nd Is Nothing Then
                MsgBox("Node '" & NodeName & "' could not be found in the file " & FilePath, MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            doc.DocumentElement.RemoveChild(nd)
            doc.Save(FilePath)
            MsgBox("Node Removed!")
        End If
    End Sub

Author

Commented:
thank you, worked perfect

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial