HandsOn Working with XML Document Nodes

1. In the same module of the Visual Basic Editor screen where you entered the ReadXMLDoc procedure in the previous hands-on exercise, enter the LearnAboutNodes procedure as shown below.

Sub LearnAboutNodes()

Dim xmldoc As MSXML2.D0MDocument50 Dim xmlNode As MSXML2.IXMLD0MNode

Set xmldoc = New MSXML2.D0MDocument50 xmldoc.async = False xmldoc.Load ("C:\Learn_XML\Shippers.xml") If xmldoc.hasChildNodes Then

Debug.Print "Number of child Nodes: " & xmldoc.childNodes.length For Each xmlNode In xmldoc.childNodes

Debug.Print "Node name:" & xmlNode.nodeName Debug.Print vbTab & "Type:" & xmlNode.nodeTypeString _

& "(" & xmlNode.nodeType & ")" Debug.Print vbTab & "Text: " & xmlNode.Text Next xmlNode End If

Set xmlDoc = Nothing End Sub

Notice that the above procedure uses the hasChildNodes property of the DOMDocument object to check whether there are any child nodes in the loaded XML file. If child nodes are found, the length property of the childNodes collection returns the total number of child nodes found. Next, the procedure loops through the childNodes collection and retrieves the node name using the nodeName property of the IXMLDOMNode object. The nodeTypeString property returns the string version of the node type (for example, processing instruction, element, text, etc.) and the nodeType property is used to return the enumeration value. Finally, the Text property of the IXMLDOMNode object retrieves the node text.

2. Position the insertion point anywhere within the code of the LearnAboutNodes procedure and choose Run | Run Sub/UserForm. The result of running the LearnAboutNodes procedure is shown below:

Number of child Nodes: 2 Node name:xml

Type:processinginstruction(7) Text: version="1.0" encoding="UTF-8" Node name:dataroot Type:element(1)

Text: 1 Speedy Express (503) 555-9831 2 United Package (503) 555-3199 3 Federal Shipping (503) 555-9931

Taking Your VBA Programming Skills to the Web

0 0

Post a comment