Link to home
Start Free TrialLog in
Avatar of arthurh88
arthurh88

asked on

Code to delete an XML attribute VB.NET 2005

<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?
Avatar of Wayne Taylor (webtubbs)
Wayne Taylor (webtubbs)
Flag of Australia image

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
ASKER CERTIFIED SOLUTION
Avatar of Wayne Taylor (webtubbs)
Wayne Taylor (webtubbs)
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of arthurh88
arthurh88

ASKER

thank you, worked perfect