Sachin Verma
Sachin Verma

Reputation: 351

How to find a specific XML node and delete its parent node?

I have an XML file that reads like this

<abc>
  <ab>value</ab>
  <aa>time</aa>
  <ac>money</ac>
</abc>
<abc>
  <ab>right</ab>
  <aa>left</aa>
  <ac>straight</ac>
</abc>

What i want is that i am able to find the node which has a value "left" and then delete its parent node so that what i get at last is

<abc>
  <ab>value</ab>
  <aa>time</aa>
  <ac>money</ac>
</abc>

Thanks in advance

Upvotes: 1

Views: 3372

Answers (1)

Bob77
Bob77

Reputation: 13267

If this was corrected to valid XML by adding a document element:

<doc>
    <abc>
        <ab>value</ab>
        <aa>time</aa>
        <ac>money</ac>
    </abc>
    <abc>
        <ab>right</ab>
        <aa>left</aa>
        <ac>straight</ac>
    </abc>
</doc>

You could do something like:

Dim DOM As MSXML2.DOMDocument
Dim Node As MSXML2.IXMLDOMNode

Set DOM = New MSXML2.DOMDocument
With DOM
    .async = False
    .preserveWhiteSpace = True
    If .Load("sample.xml") Then
        .setProperty "SelectionLanguage", "XPath"
        Set Node = .selectSingleNode("//*[.='left']")
        If Not Node Is Nothing Then
            .documentElement.removeChild Node.parentNode
            On Error Resume Next
            Kill "sample.xml"
            On Error GoTo 0
            .save "sample.xml"
            MsgBox "Done, saved as sample.xml"
        Else
            MsgBox "No ""left"" found"
        End If
    Else
        MsgBox "Load failed!" & vbNewLine & vbNewLine _
             & CStr(.parseError.errorCode) & " " _
             & .parseError.reason
    End If
End With

Upvotes: 1

Related Questions