Figure

To see objects, properties, and methods exposed by the DOM (Document Object Model), open the Object Browser after setting up a reference to the Microsoft XML type library (see Figure 17-23).

To work with an XML document, you need to create an instance of the DOMDocument object, as in the following example:

Dim myXMLDoc as MSXM2.D0MDocument30 Set myXMLDoc = New MSXML2.D0MDocument30

To make the instantiated DOMDocument object useful, you should load it with some data. The following VBA procedure demonstrates how to get started with the XML DOM. You will perform the following tasks:

■ Create an instance of the DOMDocument

■ Load XML information from a file using the Load method

■ Use the DOMDocument object's XML property to retrieve the raw data

■ Use the DOMDocument object's Text property to retrieve the text stored in nodes

The following exercise demonstrates how to read XLM documents programmatically.

1. Enter the following Load_ReadXMLDoc procedure in a new module. Change the path to point to the Courses.xml file on your hard disk.

2. Run the procedure and examine the results in the Immediate window and in an Excel spreadsheet.

Sub Load_ReadXMLDoc()

' Create an instance of the DOMDocument Dim xmldoc As MSXML2.D0MDocument30 Set xmldoc = New MSXML2.D0MDocument30 ' Disable asynchronous loading xmldoc.async = False ' Load XML information from a file

If xmldoc.Load("C:\JK_B00KS_ALL\Excel_EN_2002\" _ & "ChaptersNew\Chapter_17\Courses.xml") Then ' Use the DOMDocument object's XML property to ' retrieve the raw data Debug.Print xmldoc.XML

' Use the DOMDocument object's Text poperty to ' retrieve the actual text stored in nodes Sheets(2).Range("A1").Value = xmldoc.Text End If End Sub

The XML DOM has two methods for loading XML information: Load and LoadXML. Use the Load method to load XML information from a text file. Use the LoadXML method when loading from a string in memory (we will discuss the Stream object later in this chapter). MSXML uses an asynchronous loading mechanism by default for working with documents. Asynchronous loading allows you to perform other tasks during long database operations, such as providing feedback to the user as MSXML parses the XML file or giving the user the chance to cancel the operation. Before calling the Load method, however, it's a good idea to set the Asynch property of the DOMDocument object to False to ensure that when the load returns, the entire document has finished loading. The Load method returns True if it successfully loaded the data and False otherwise. Having loaded the data into a DOMDocument object, you can use the XML property to retrieve the raw data or use the Text property to obtain the text stored in document nodes.

0 0

Post a comment