Looping through XML using VBA Looping through XML using VBA vba vba

Looping through XML using VBA


Option ExplicitPrivate Const xml As String = "<PMRData>" & _                                  "<Staff StaffName='Person 1'>" & _                                    "<Openings>1.1</Openings>" & _                                    "<Closures>1.11</Closures>" & _                                  "</Staff>" & _                                  "<Staff StaffName='Person 2'>" & _                                    "<Openings>1.2</Openings>" & _                                    "<Closures>1.22</Closures>" & _                                  "</Staff>" & _                                  "<Staff StaffName='Person 3'>" & _                                    "<Openings>1.3</Openings>" & _                                    "<Closures>1.33</Closures>" & _                                  "</Staff>" & _                                "</PMRData>"Sub test()    Dim xDoc As DOMDocument    Set xDoc = New DOMDocument    If Not xDoc.LoadXML(xml) Then        Err.Raise xDoc.parseError.ErrorCode, , xDoc.parseError.reason    End If    Dim list As IXMLDOMNodeList    Set list = xDoc.SelectNodes("//PMRData/Staff")    Dim attr As IXMLDOMAttribute    Dim node As IXMLDOMNode    Dim childNode As IXMLDOMNode    For Each node In list        Set attr = node.Attributes.getNamedItem("StaffName")        If (Not attr Is Nothing) Then            Debug.Print attr.BaseName & " " & attr.Text        End If        If (node.HasChildNodes) Then            For Each childNode In node.ChildNodes                Debug.Print childNode.BaseName & " " & childNode.Text            Next childNode        End If    Next nodeEnd Sub

Output:

StaffName Person 1Openings 1.1Closures 1.11StaffName Person 2Openings 1.2Closures 1.22StaffName Person 3Openings 1.3Closures 1.33