Read XML child node Attribute on VBA with oDOC

2019-09-19 01:20发布

I have a list of different animals (following XML file), some of the animals have children, I wrote something that print all children animal names it won't work it say "object dosen't support this property or method" If I would replace this line : Set list =oDoc.SelectSingleNode("/animal/cat[(@ID)=""17""]")

to that one: Set list = xDoc.SelectNodes("/animal/cat[(@ID)=""17""]") my code works perfect , but I can't replace it because other method required that list will defined like that : Set list = oDoc.SelectSingleNode("/animal/cat[(@ID)=""17""]")

any idea, to solve my problem?

note:not every animal have a child, and if they have, some will have 4 children some 3 etc.. (I can't know how many children animal can have)

VBA (using XDoc):

Sub test()

    Dim xml As String
          xml = ("C:.....\example2.xml")
    Dim xDoc As DOMDocument
    Set xDoc = New DOMDocument

    Dim list As Object

    Dim attr As IXMLDOMAttribute
    Dim node As IXMLDOMNode
    Dim childNode As IXMLDOMNode
    Dim oDoc As New MSXML2.DOMDocument60


   oDoc.validateOnParse = True

  'xDoc.Load xml 
  'oDoc.Load xml

  ' Set list = XDoc.SelectNodes("/animal/cat[(@ID)=""17""]")
  ' Set list = oDoc.SelectSingleNode("/animal/cat[(@ID)=""17""]")

  For Each node In list <-- **this line will not work!!**
        If (node.HasChildNodes) Then

            For Each childNode In node.ChildNodes
            Set attr = childNode.Attributes.getNamedItem("Name")
                 Debug.Print attr.Text
            Next childNode
        End If
    Next node

End Sub

XML:

<animal>
           <dog ID="16" Name="Lucy"/>
           <cat ID="156" Name="Chloe"/>
           <cat ID="17" Name="GAL">
                 <child ID="173" Name="Tigger"/>
                 <child ID="1256" Name="Angel"/>
                 <child ID="256" Name="Peanut"/>
           </cat>
           <cat ID="18" Name="Charlie">
                 <child ID="173" Name="Smokey"/>
           </cat>
  </animal>

0条回答
登录 后发表回答