Search code examples
xmlvb.netxmldocument

Delete a specific XML Element


I'd like to delete a whole "TableData" Elemt with a specific ID (ID 10 in this case) from my xml:

<DataPaths>
  <TableData>
    <ID>10</ID>
    <TablePath>C:\Users\Tom\Test.xls</TablePath>
    <TableName>TestName</TableName>
    <Mode>TestMode</Mode>
  </TableData>
</DataPaths>

I tried two different solutions and I think I'm almost there.

Solution 1:

Dim XmldocDel As New XmlDocument()
        XmldocDel.Load("" & buildSettingsPath)
        Dim node As XmlNode
        node = XmldocDel.SelectSingleNode("//DataPaths/TableData[ID = '10']")

        If MessageBox.Show("Are you sure you want to delete:", MessageBoxButtons.YesNo) = DialogResult.Yes Then
            If node IsNot Nothing Then
            node.ParentNode.RemoveChild(node)
            'node.ParentNode.RemoveAll()

            XmldocDel.Save("" & buildSettingsPath)
            Reload()
        Else
            MessageBox.Show("No node found")
        End If

        Else
            Exit Sub
        End If

I'm getting a null Exception here.

Solution 2:

Dim clientNodes = XmldocDel.SelectNodes("//ID")
        For Each elem As Xml.XmlElement In clientNodes
            If elem.InnerText = "10" Then
                elem.ParentNode.RemoveChild(elem)
                Exit For
            End If
        Next

This will simply do nothing.


Solution

  • Using solution 1, since you want to delete the whole TableData element, the XPath should've selected TableData element instead of ID element :

    .....
    node = XmldocDel.SelectSingleNode("//DataPaths/TableData[ID = '10']")
    .....
    

    *) updated above XPath a bit. Looking at the XML posted, the first step should be DataPaths instead of DataSetPaths.

    UPDATE :

    Your actual XML has default namespace. So in this case, you need to register a prefix mapped to the default namespace URI using XmlNamespaceManager. Use the registered prefix in the XPath, and pass the namespace manager as 2nd parameter of SelectSingleNode() method :

    Dim nsManager As New XmlNamespaceManager(New NameTable())
    nsManager.AddNamespace("d", "http://tempuri.org/DataPaths.xsd")
    .....
    node = XmldocDel.SelectSingleNode("//d:DataPaths/d:TableData[d:ID = '10']", nsManager)
    .....
    

    [.NET fiddle demo]