Jiminy Cricket
Jiminy Cricket

Reputation: 1377

MSXML Remove Node Not Behaving As Expected

I am trying to delete a node from the following XML - Data below is only representative of the acutal data:

<StaffMembers>
    <Staff Name="Test1" Date="Date1"/>
    <Staff Name="Test2" Date="Date2"/>
</StaffMembers>

My code is as follows:

Sub DeleteRecord(strName as string, strDate as string)

'Load Document

    Set xList = xDoc.SelectNodes("//StaffMembers/")
    for each xNode in xList
             If xNode.Attributes.Length > 0 And xNode.Attributes.getNamedItem("Date").NodeValue = strDate Then
                 xnode.parentnode.removechild xnode
                 exit for
             End if
    next xNode

'Save Document

End Sub

Resulting XML - as you can see, it is not complete:

<StaffMembers>
    <Staff Name="Test1" Date="Date1"/>
    <Staff Name="Tes

The correct node is selected, but it is only partially deleted. If I open the resulting XML in Notepad, some of the text of the node remains. Can anyone explain this?

Edit:

I have tried removing each Attribute individually before removing the Element. This suffers from the same problem.

Thanks

Upvotes: 1

Views: 846

Answers (3)

Jiminy Cricket
Jiminy Cricket

Reputation: 1377

Thanks for the replies. I've managed to narrow the problem down to having a slow network connection. The corruption does not occur when saving to a local folder.

Thanks

Upvotes: 0

DavidRR
DavidRR

Reputation: 19397

Here's an XPath selector that will select those nodes which are named Test2 or Test3:

xDoc.SelectNodes("//Staff[@Name = ""Test2"" || @Name = ""Test3""]")

For the test VBScript program below I get the following output after deleting those nodes:

<StaffMembers>
  <Staff Name="Test1" Date="Date1"/>
  <Staff Name="Test4" Date="Date4"/>
</StaffMembers>

Test Program:

Option Explicit

DeleteRecord "Test2", "Test3"

Sub DeleteRecord(name1, name2)
    Dim xDoc : Set xDoc = CreateObject("Msxml2.DOMDocument")
    xDoc.LoadXML GetXml()

    Dim xList : Set xList = xDoc.SelectNodes _
        ("//Staff[@Name = """ & name1 & """ || @Name = """ & name2 & """]")

    Dim xNode
    For Each xNode in xList
        xNode.ParentNode.RemoveChild xNode
    Next

    WScript.Echo xDoc.Xml
End Sub

Function GetXml()
    Dim NL : NL = vbNewLine

    GetXmL = _
        "<StaffMembers>" &NL& _
        "  <Staff Name='Test1' Date='Date1'/>" &NL& _
        "  <Staff Name='Test2' Date='Date2'/>" &NL& _
        "  <Staff Name='Test3' Date='Date3'/>" &NL& _
        "  <Staff Name='Test4' Date='Date4'/>" &NL& _
        "</StaffMembers>"
End Function

Upvotes: 1

har07
har07

Reputation: 89285

You can use XPath to select nodes with matching attribute criteria. For example :

.....
Set xList = xDoc.SelectNodes("//StaffMembers/Staff[@Date='Date2']")
For Each xnode In xList
    xnode.ParentNode.RemoveChild xnode
Next xnode
.....

Upvotes: 1

Related Questions