Question

I'm trying to display all of the nodes in an xml document. The code I have thus far (shown below) only displays the two child nodes of the root node, which is a problem because the majority of the child nodes have child nodes as well.

Here's the code I have so far:

Sub countXMLNodes()

Dim xDoc As DOMDocument
Set xDoc = New DOMDocument
If Not xDoc.Load(filepath) Then
    MsgBox ("failed to load xml document")
End If

Dim list As IXMLDOMNodeList
Set list = xDoc.SelectNodes("//PropertiesAndDocument")


Dim node As IXMLDOMNode
Dim childNode As IXMLDOMNode

For Each node In list
    If (node.HasChildNodes) Then
        For Each childNode In node.ChildNodes
            MsgBox (childNode.BaseName)
        Next childNode
    End If
Next node

End Sub
Was it helpful?

Solution

Try to adjust the following example code to work for your intended purpose:

Public Sub LoadDocument()
Dim xDoc As DOMDocument
Set xDoc = New DOMDocument
xDoc.validateOnParse = False
If xDoc.Load("c:/temp/tmp/test.xml") Then
   ' The document loaded successfully.
   ' Now do something intersting.
   DisplayNode xDoc.ChildNodes, 0
Else
   ' The document failed to load.
   ' See the previous listing for error information.
End If
End Sub

Public Sub DisplayNode(ByRef Nodes As IXMLDOMNodeList, _
   ByVal Indent As Integer)

   Dim xNode As IXMLDOMNode
   Indent = Indent + 2

   For Each xNode In Nodes
      Debug.Print Space$(Indent) & xNode.ParentNode.NODENAME & _
        ":" & xNode.nodeTypeString & ":" & xNode.NodeValue

      If xNode.HasChildNodes Then
         DisplayNode xNode.ChildNodes, Indent
      End If
   Next xNode
End Sub

Source: http://msdn.microsoft.com/en-us/library/aa468547.aspx#beginner_howuse

I came across this example while adjusting your code for recursion. It seems to me it's better for me to share the original example so you can try to figure it out yourself with it. Let me know if it's still not clear.

I changed a small part of the code above to work towards your goal of listing all the XML elements (I use debug.print, you can add them to your list). For the following example:

<lv1> <lv2> <lv3> <lv4> test4 </lv4> <lv4> test4.2 </lv4> </lv3> </lv2> <lv2> test 2 </lv2> </lv1>

This gives the next result:

#document:element: lv1:element: lv2:element: lv3:element: lv4:text: test4 lv3:element: lv4:text: test4.2 lv1:element: lv2:text: test 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top