HandsOn Retrieving Specific Information from Element Nodes

1. In the Visual Basic Editor Code window, in the same module where you entered the previous procedures, enter the SelectNodesByCriteria procedure as shown below.

Sub SelectNodesByCriteria()

Dim xmldoc As MSXML2.D0MDocument50 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.selectNodes("//CompanyName") If Not (xmlNodeList Is Nothing) Then For Each myNode In xmlNodeList Debug.Print myNode.Text If myNode.Text = "Federal Shipping" Then myNode.Text = "Airborne Express" xmldoc.Save "C:\Learn_XML\Shippers.xml" End If Next myNode End If

Set xmlDoc = Nothing End Sub

The SelectNodesByCriteria procedure creates the IXMLDOMNodeList object that represents a collection of child nodes. The selectNodes method applies the specified pattern to this node's context and returns the list of matching nodes as IXMLDOMNodeList. The expression used by the selectNodes method specifies that all the CompanyName element nodes should be included in the node list.

You can use the Is Nothing conditional expression to find out whether a matching element was found in the loaded XML file. If the matching elements were found in the IXMLDOMNodeList, the procedure iterates through the node list and prints each element node text to the Immediate window. In addition, if the node element's text value is Federal Shipping, the procedure replaces this value with Airborne Express. The Save method of the DOMDocument is used to save the changes in the Shippers.xml file.

Taking Your VBA Programming Skills to the Web

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

Speedy Express United Package Federal Shipping o

0 0

Post a comment