HandsOn Retrieving Information from Element Nodes

1. In the Visual Basic Editor Code window, enter the following IterateThru-Elements procedure below the last procedure code (see Hands-On 29-10).

Sub IterateThruElements()

Dim xmldoc As MSXML2.D0MDocument50 Dim xmlNode As MSXML2.IXMLD0MNode Dim xmlNodeList As MSXML2.IXMLD0MNodeList Dim myNode As MSXML2.IXMLD0MNode

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

Set xmlNodeList = xmldoc.getElementsByTagName("*")

For Each xmlNode In xmlNodeList

For Each myNode In xmlNode.childNodes If myNode.nodeType = N0DE_TEXT Then

Debug.Print xmlNode.nodeName & "=" & xmlNode.Text End If Next myNode Next xmlNode Set xmlDoc = Nothing End Sub

The IterateThruElements procedure retrieves the XML document name and the corresponding text for all the text elements in the Shippers.xml file. Notice that this procedure uses two For Each.. .Next loops. The first one (the outer For Each.. .Next loop) iterates through the entire collection of element nodes. The second one (the inner For Each.. .Next loop) uses the nodeType property to find only those element nodes that contain a single text node.

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

ShipperID=1

CompanyName=Speedy Express Phone=(503) 555-9831 ShipperID=2

CompanyName=United Package Phone=(503) 555-3199 ShipperID=3

Part V

CompanyName=Federal Shipping Phone=(503) 555-9931

0 0

Post a comment