Assuming your XML is in cell "A2", the first problem is that your line
Set oParentNode = xmlDoc.DocumentElement.SelectNodes("ResponseBody")(0)
Returns nothing
. Change it to
Set oParentNode = xmlDoc.DocumentElement
and the code will at least have something to process.
EDITs 1&2
The other problem is that a node-inside-a-node will not give the right output. To address that, you need to change your List_ChildNodes
function slightly. The first modification worked for the examples you had provided, but not for the later one, which does not get parsed correctly with the code I provided earlier. So I added an error trap which ensures that even this XML is read (what I believe to be) correctly. The trick of using On Error Resume Next
is essentially the VBA equivalent of a Try ... Catch
statement (except that the "catch" is: "set L to zero if there's an error. We're actually setting L to zero first, and don't overwrite that on error. Same thing, different order. One of those tricks they don't teach in school!)
Sub List_ChildNodes(oParentNode, i, NameColumn, ValueColumn)
Dim L As Integer
For Each oChildNode In oParentNode.ChildNodes
L = 0
Err.Clear
On Error Resume Next
L = oChildNode.ChildNodes(0).ChildNodes.Length
If L > 0 Then
Call List_ChildNodes(oChildNode, i, NameColumn, ValueColumn)
Else
If Not oChildNode.Text = "" Then
Cells(i, NameColumn) = oChildNode.tagName
Cells(i, ValueColumn) = oChildNode.Text
i = i + 1
End If
End If
Next
End Sub
I have tested the latest version with the bigger XML fragment that you provided, and it appeared to parse without a glitch. I wasn't going to go through it line by line to check...