Microsoft Access Database Development With VBA

Introduction to XML in Microsoft Windows

 

Introduction to the MSXML Library

 

Overview

The Extensible Markup Language, or XML, is standardized by the W3C (http://www.w3c.org) organization. To make it possible to use XML in its operating systems, Microsoft created a library named MSXML, which stands for Microsoft XML Core services.

Because Microsoft XML Core services is a separate library, to use it in Microsoft Access, you must "load" it. To do this, you have two options. One option is to graphical load the library. Another option is to programmatically do it.

To graphically load MSXML, on the main menu of Microsoft Visual Basic, click Tools -> References... In the References dialog box, click the check box of the latest version of Microsoft XML. Click OK. To programmatically load MSXML, you should first (make sure you get the latest release of the MSXML library from the Microsoft web site and) know the version of MSXML installed on your computer or the version that is installed in your users' computers. Declare a variable of type Object. To initialize it, call the global CreateObject() function and pass it the MSXML library you want to use. This can be done as follows:

Private Sub cmdLoadXMLLibrary_Click()
    Dim xmlDocument As Object

    Set xmlDocument = CreateObject("MSXML2.DOMDocument.3.0")

    Set xmlDocument = Nothing
End Sub

From then, you can use Microsoft XML Core services in your Microsoft Access project.

Practical LearningPractical Learning: Introducing MSXML

  1. Start Microsoft Access
  2. On the opening page, click Blank Desktop Database
  3. In the File Name text box replace the file name with Exercise4
  4. Click CREATE
  5. Close the default table without saving it
  6. On the Ribbon, click CREATE and, in the Forms section, click Form Design
  7. In the Controls section of the Ribbon, click the button Button and click the form. If the wizard starts, click Cancel
  8. Right-click the button of the form and click Build Event...
  9. In the Choose Builder dialog box, click Code Builder and click OK
  10. To load the MSXML library, on the main menu of Microsoft Visual Basic, click Tools -> References...
  11. In the References dialog box, click the check box of Microsoft XML, v6.0

    Microsoft XML Core services

  12. Click OK

Interfaces, Classes, and Objects in MSXML

Like a traditional programming library, Microsoft XML Core services provides many types of objects. As you may know already, a class is a building block or a way to describe what an object looks like. It is like the architural design of a house. It is not the house itself but it describes how a house built from that design should look like. A class is supposed to be complete in the sense that it gives a complete description (or provides a complete structural description) of the objects that will be created or built from it.

Another type of object in a library is called an interface. An interface is like a class, which specifies the structure of an object. In the traditional programming sense, an interface is (usually) a (n incomplete) structure from which actual classes can be built (we say that it is an abstract from which actual classes can be created). This means that, in the traditional sense of computer programming, an interface is a vague description of a structure. An example of an interface would be a residence (Is it a house? Is it a commercial building? Is it an appartment complex? Is it a moving house? Is it a tent? etc). Once an interface exists, more appropriate and precise classes are created from it (such as houses, tents, etc). By tradition, the name of an interface starts with I (this distinguishes it from a class; but this is not a rule, just an indication).

Without going through all the boring (and probably uncessary) details (there is no way we can go through all the issues to know about object-oriented programming (OOP) here), the few things to know are that:

  • A class can be directly created from scratch. Such a class defines its own properties and methods
  • A class may be derived from another class. Usually, the child class adds one or more new properties and/or methods to those of the parent class
  • A class may be derived from an interface (by tradition, we don't say that a class is derived from an interface; we say that a class "implements" an interface). The class can simply implement the desired behavior of the interface. For example, the class can (in reality must) implement (all) the methods listed in the interface. The class may (or may not) add new methods (this depends on the person who implemented the class)
  • An interface serves as a foundation for other interfaces and classes. This means that:
    • An interface can be derived from another interface. Usually, the child interface adds new properties and/or methods from the parent interface
    • To use an interface, an existing class must implement that interface. This means that, while an interface can exist by itself, if there is no class that implements that interface, the interface cannot be used (for example to declare a variable)

The MSXML library provides many classes and interfaces. To use any of them, you can (in most cases, you must) declare a variable of the desired type and appropriately initialize it.

Introduction to the Document Object Model

While creating an XML document, you must follow some rules in order to get a valid document. An XML document that follows all the necessary rules is said to be "well-formed". The XML rules are standardized by the W3C Document Object Model (DOM). To support these standards, Microsoft XML Core services provides a class named DOMDocument that makes it possible to start an XML document, to populate it with the desired contents, and to perform many other related operations on the contents of the document.

Before using a DOM, declare a variable of type DOMDocument and initialize it using the New operator. This can be done as follows:

Private Sub cmdCreateDOMDocument_Click()
    Dim docXMLDOM As DOMDocument
    
    Set docXMLDOM = New DOMDocument
End Sub

This causes the DOM object to be loaded into the computer's memory and start using resources. Eventually, after using the object, you should remove it from memory. This is done by assigning Nothing to it. This can be done as follows:

Private Sub cmdCreateDOMDocument_Click()
    Dim docXMLDOM As DOMDocument
    
    Set docXMLDOM = New DOMDocument
    
    Set docXMLDOM = Nothing
End Sub

Providing XML Code Using DOMDocument

If you already know or have the XML code you want to use, the DOMDocument class allows you to provide it. This is done using one of the class's methods named loadXml. Its syntax is:

Public Function loadXml(ByVal bstrXML As String) As Boolean

This method takes a String as argument and returns a Boolean value. The DOMDocument.loadXml() method doesn't create an XML file, it only allows you to provide or create XML code. The code can be created as argument. You can also first declare and initialize a String variable with the XML code, then pass it as argument to the DOMDocument.loadXml() method.

Practical LearningPractical Learning: Loading XML Code

  • Implement the event as follows:
    Private Sub Command0_Click()
        Dim docXMLDOM As DOMDocument
        
        docXMLDOM.loadXML ""
    
        Set docXMLDOM = Nothing
    End Sub

Saving/Opening an XML File

 

Saving an XML Document

Probably the most common way to create an XML document in Microsoft Windows consists of using Notepad or any other text editor. After opening the text editor, you can enter the necessary lines of code. After creating the file, you must save it. When saving it, you can include the name of the file in double-quotes. You can also first set the Save As Type combo box to All Files and then enter the name of the file with the .xml extension.

Saving a DOM Object

If you call the DOMDocument.loadXml() method, only the XML code is created, not the file. To let you create the Windows file, the DOMDocument is equipped with a method named save(). Its syntax is:

Public Sub save(ByVal FileName As String)

This method takes one argument that can be a valid file name and must include the .xml extension. You can also pass the whole path where the file must be located.

Practical LearningPractical Learning: Saving an XML Document

  • Change the code as follows:
    Private Sub Command0_Click()
        Dim docXMLDOM As DOMDocument
       
        docXMLDOM.loadXML ""
        
        docXMLDOM.Save "ContractWorkers.xml"
    
        Set docXMLDOM = Nothing
    End Sub

Opening an XML File

Probably the easiest way to open an XML file is with a text editor such as Notepad. You can also open the file using a Web browser or an appropriate application that recognizes XML code.

To let you open an XML file, the DOMDocument class is equipped with a method named load. Its syntax is:

Public Function load(ByVal FileName As String)

The method takes as argument the name or path of the file. Here is an example of calling it:

Private Sub cmdCreateDOMDocument_Click()
    Dim docXMLDOM  As Object
    
    Set docXMLDOM = CreateObject("MSXML2.DOMDocument.3.0")
    
    docXMLDOM.Load "Employees.xml"

    Set docXMLDOM = Nothing
End Sub

You can also provide a complete path to the file.

Practical LearningPractical Learning: Opening an XML File

  • Change the code as follows:
    Private Sub Command0_Click()
        Dim docXMLDOM As DOMDocument
        
        If Dir("ContractWorkers.xml") = "" Then
            docXMLDOM.loadXML ""
        
            docXMLDOM.Save "ContractWorkers.xml"
        Else
            docXMLDOM.Load "ContractWorkers.xml"
        End If
    
        Set docXMLDOM = Nothing
    End Sub
    
    

Introduction to the Structure of an XML Document

 

Introduction to XML Nodes

An XML document appears as an upside-down tree with many branches and leaves. Each of these objects is called a node. To support the nodes of an XML document, the MSXML library provides an interface named IXMLDOMNode. This is the ancestor to all types of nodes.

Introduction to Node Types

An XML document can contain various types of nodes. The categories or possible types of nodes are identified by an enumeration named DOMNodeType. Each of the different types of nodes we will use has a corresponding member in that enumeration.

Giving Processing Instructions

An XML document can start with the type of character scheme it is using. This is known as the encoding declaration. That declaration gives instructions to the parser on the types or groups of characters and symbols used in your document. This is done with a line as follows:

<?xml version="1.0" encoding="utf-8"?>

Remember that, in your VBA code, you can use the single-quote inside a string, or you can double the double-quote. Here are examples:

Private Sub cmdCreateProcessingInstructions_Click()
    Dim docXMLDOM  As Object
    
    Set docXMLDOM = CreateObject("MSXML2.DOMDocument.3.0")
        
    docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8""?>"

    Set docXMLDOM = Nothing
End Sub

To support processing instructions, the MSXML library provides an interface named IXMLDOMNode. On the other hand, to help you create an encoding declaration, the DOMDocument class is equipped with a method named createProcessingInstruction. Its syntax is:

Public Function createProcessingInstruction(ByVal target, ByVal data As String) As IXMLDOMProcessingInstruction


This method takes two arguments. The first argument can be passed as "xml". The second argument specifies the version of XML used. In most cases, this should be set to "version='1.0'". This method returns an object of type IXMLDOMProcessingInstruction. This means that you can call the DOMDocument.createProcessingInstruction() method and assign it to an IXMLDOMProcessingInstruction variable you would have previously declared. In reality, you have two versions. You can declare a variable of type IXMLDOMProcessingInstruction and use it. Here is an example:

Private Sub cmdCreateProcessingInstructions_Click()
    Dim docXMLDOM  As DOMDocument
    Dim piDeclaration As IXMLDOMProcessingInstruction
    
    Set docXMLDOM = New DOMDocument
    
    Set piDeclaration = docXMLDOM.createProcessingInstruction("xml", "version='1.0'")

    Set docXMLDOM = Nothing
End Sub

An alternative is to use a variable of type IXMLDOMNode.

Practical LearningPractical Learning: Creating Processing Instructions

  • Change the code as follows:
    Private Sub cmdCreateEmployee_Click()
        Dim docXMLDOM As DOMDocument
        
        If Dir("ContractWorkers.xml") = "" Then
            docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>"
        
            docXMLDOM.Save "ContractWorkers.xml"
        Else
            docXMLDOM.Load "ContractWorkers.xml"
        End If
    
        Set docXMLDOM = Nothing
    End Sub

Introduction to XML Elements

 

Elements Fundamentals

An XML document is made of small objects or sections named elements. Each element is created based on strict rules. A classic XML element is made of three parts:

  • A start-tag made of <, a name, and >. An example is <Director>
  • A value
  • An end-tag made of </, the same name as the start tag, and >

There are rules you must follow when naming an element

  • XML is case-sensitivite. This means that XML, xml, and Xml are not the same
  • The name cannot start with the letters X (uppercase or lowercase), followed by M (uppercase or lowercase), and followed by L (uppercase or lowercase) in a combination
  • The name must start with a letter or an underscore
  • After the starting letter or underscore, the name can contain letters, digits, hyphens, or underscores
  • The name must be in one word

The value can be anything, but some letters may not automatically display rightly. Such letters must be appropriatly formatted.

To support XML elements, the MSXML library is equipped with an interface named IXMLDOMElement. In the DOMNodeType enumeration, the XML element is represented by the NODE_ELEMENT member.

The Root Element

Every XML document must have one particular element that either is the only element in the document or acts as the parent of all the other elements of the same document. This element is referred to as the root. If there are many elements in an XML document, one of them must serve as the root. To give you access to the root element of an XML document, the DOMDocument class of the MSXML library has a property named documentElement. To specify that an element is the root, you can assign its reference to this property (we will see many examples). If an XML document exists already, to access its root, get a reference to the DOMDocument.documentElement property.

Practical LearningPractical Learning: Creating a Root Element

  • Change the code as follows:
    Private Sub cmdCreateEmployee_Click()
        Dim docXMLDOM As DOMDocument
        Dim nodRoot As IXMLDOMElement
    
        If Dir("ContractWorkers.xml") = "" Then
            docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>"
        
            docXMLDOM.Save "ContractWorkers.xml"
        Else
            docXMLDOM.Load "ContractWorkers.xml"
            
            Set nodRoot = docXMLDOM.documentElement
        End If
    
        Set docXMLDOM = Nothing
    End Sub

Fundamentals of Creating an XML Element

   

Introduction to Creating an XML Element

Since IXMLDOMElement is an interface, in order to use it, you must obtain its value from another class. To assist you with creating an element, the DOMDocument class is equipped with a method named createElement. Its syntax is:

Public Function createElement(ByVal tagName As String) As IXMLDOMElement

This method takes one argument and returns an element as a IXMLDOMElement object. When calling this method, you get a reference to the newly created element. If that element is the root, assign it to the documentElement property of the DOMDocument class. Here is an example:

Private Sub cmdCreateElement_Click()
    Dim docXMLDOM  As DOMDocument
    Dim nodElement As IXMLDOMElement
    
    Set docXMLDOM = New DOMDocument
    
    Set nodElement = docXMLDOM.createElement(...)
    
    Set docXMLDOM.documentElement = nodElement
    
    Set docXMLDOM = Nothing
End Sub

The Name of an Element

As mentioned earlier, the primary formula of an element is a start tag, a name, and an end tag. The name of an element is the string that represents the tag. For example, in <Director>, the word Director is the name of the element. An element must have at least a start-tag. As mentioned in the previous section, you can create an element by calling the DOMDocument.createElement() method. This method takes one argument as the name of the element to be created. When calling this method, assign its returned value to an IXMLDOMNode-based variable, such as an IXMLDOMElement object, you would have declared. Here is an example:

Private Sub cmdCreateElement_Click()
    Dim docXMLDOM  As DOMDocument
    Dim nodElement As IXMLDOMElement
    
    Set docXMLDOM = New DOMDocument
    
    Set nodElement = docXMLDOM.createElement("houses")
    Set docXMLDOM.documentElement = nodElement

    docXMLDOM.Save "C:\Exercises\Houses1.xml"
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

<?xml version="1.0"?>
<house/>

If an element exists already, to let you get its name, the IXMLDOMNode interface is equipped with a property named tagName. Here is an example of accessing it:

Private Sub cmdCreateDOMDocument_Click()
    Dim docXMLDOM  As DOMDocument
    Dim nodElement As IXMLDOMElement
    
    Set docXMLDOM = New DOMDocument
    
    Set nodElement = docXMLDOM.createElement("houses")
    Set docXMLDOM.documentElement = nodElement

    MsgBox nodElement.tagName
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

The Name of an Element

The Value of an Element

The value of an element is referred to as its text. To support such a value, the IXMLDOMNode interface is equipped with a String-based property named Text. To specify the name of an element, assign the desired string to its variable. Here is an example:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As DOMDocument
    Dim nodElement As IXMLDOMElement
    
    Set docXMLDOM = New DOMDocument
    
    Set nodElement = docXMLDOM.createElement("house")
    
    nodElement.Text = "Single Family"
    
    Set docXMLDOM.documentElement = nodElement
    
    docXMLDOM.Save "C:\Exercises\Houses2.xml"
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

<?xml version="1.0"?>
<house>Single Family</house>

If an element exists already, to find out about its value, you can get its Text value.

The Values of an XML Document

To let you get all the values of an XML document, the IXMLDOMNode interface is equipped with a property named xml. Here is an example of accessing it:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As DOMDocument
    
    Set docXMLDOM = New DOMDocument
    docXMLDOM.Load "C:\Exercises\Videos.xml"
    
    MsgBox docXMLDOM.xml
    
    Set docXMLDOM = Nothing
End Sub

If an element exists already, to find out about its value, you can get its Text value.

Character Entities in an Element Value

Besides the obvious types of values, you may want to display special characters as values of elements. Consider the following example:

<FullName>Sylvie <Nellie> Aronson</FullName>

If you try using this XML document, for example, if you try displaying it in a browser, you would receive an error. The reason is that when the parser reaches the <FullName>Sylvie <Nellie> Aronson</FullName> line, it thinks that <Nellie> is a tag but then <Nellie> is not closed. The parser concludes that the document is not well-formed, that there is an error. For this reason, to display a special symbol as part of a value, you can use its character code. For example, the < (less than) character is represented with &lt and the > (greater than) symbol can be used with &gt;. Therefore, the above code can be corrected as follows:

<FullName>Sylvie &lt;Nellie&gt; Aronson</FullName>

Here is a list of other codes you can use for special characters:

 
 
Code Symbol Code Symbol Code Symbol Code Symbol Code Symbol
&apos; ' &#067; C &#106; j &#179; ³ &#218; Ú
&lt; < &#068; D &#107; k &#180; ´ &#219; Û
&gt; > &#069; E &#108; l &#181; µ &#220; Ü
&amp; & &#070; F &#109; m &#182; &#221; Ý
&quot; " &#071; G &#110; n &#183; · &#222; Þ
&#033; ! &#072; H &#111; o &#184; ¸ &#223; ß
&#034; " &#073; I &#112; p &#185; ¹ &#224; à
&#035; # &#074; J &#113; q &#186; º &#225; á
&#036; $ &#075; K &#114; r &#187; » &#226; â
&#037; % &#076; L &#115; s &#188; ¼ &#227; ã
&#038; & &#077; M &#116; t &#189; ½ &#228; ä
&#039; ' &#078; N &#117; u &#190; ¾ &#229; å
&#040; ( &#079; O &#118; v &#191; ¿ &#230; æ
&#041; ) &#080; P &#119; w &#192; À &#231; ç
&#042; * &#081; Q &#120; x &#193; Á &#232; è
&#043; + &#082; R &#121; y &#194; Â &#233; é
&#044; , &#083; S &#122; z &#195; Ã &#234; ê
&#045; - &#084; T &#123; { &#196; Ä &#235; ë
&#046; . &#085; U &#125; } &#197; Å &#236; ì
&#047; / &#086; V &#126; ~ &#198; Æ &#237; í
&#048; 0 &#087; W &#160; empty &#199; Ç &#238; î
&#049; 1 &#088; X &#161; ¡ &#200; È &#239; ï
&#050; 2 &#089; Y &#162; ¢ &#201; É &#240; ð
&#051; 3 &#090; Z &#163; £ &#202; Ê &#241; ñ
&#052; 4 &#091; [ &#164; ¤ &#203; Ë &#242; ò
&#053; 5 &#092; \ &#165; ¥ &#204; Ì &#243; ó
&#054; 6 &#093; ] &#166; ¦ &#205; Í &#244; ô
&#055; 7 &#094; ^ &#167; § &#206; Î &#245; õ
&#056; 8 &#095; _ &#168; ¨ &#207; Ï &#246; ö
&#057; 9 &#096; ` &#169; © &#208; Ð &#247; ÷
&#058; : &#097; a &#170; ª &#209; Ñ &#248; ø
&#059; ; &#098; b &#171; « &#210; Ò &#249; ù
&#060; < &#099; c &#172; ¬ &#211; Ó &#250; ú
&#061; = &#100; d &#173; ­ &#212; Ô &#251; û
&#062; > &#101; e &#174; ® &#213; Õ &#252; ü
&#063; ? &#102; f &#175; ¯ &#214; Ö &#253; ý
&#064; @ &#103; g &#176; ° &#215; × &#254; þ
&#065; A &#104; h &#177; ± &#216; Ø &#255; ÿ
&#066; B &#105; i &#178; ² &#217; Ù &#256; Ā

There are still other codes to include special characters in an XML file.

Empty Elements

An element may not have a value but only a name. Consider the following example:

<video></video>

In this case, the video element doesn't have a value. It is called an empty element. When a tag is empty, the Text property of its IXMLDOMNode object would return an empty value.

Nesting an Element

As mentioned already, every XML document must have a primary element called the root. That root can exist by itself in the document, but if the document contains more than one element, the other elements must be created inside the root element. Such elements are created outside and on the right side of the start tag of the root but before the end tag. Here are examples of elements named FullName, PhoneNumber, and EmailAddress created inside a root element named Customer:

<?xml version="1.0" encoding="UTF-8"?>
<Customer>
  <FullName></FullName>
  <PhoneNumbers></PhoneNumbers>
  <EmailAddress></EmailAddress>
</Customer>

When an element B has been created inside another element A, Element B is said to be nested inside of Element A. We can also say that Element A is nesting Element B. In the same way, various combinations of nesting elements can be created. Here are examples:

<?xml version="1.0" encoding="UTF-8"?>
<Customer>
  <FullName>
    <FirstName></FirstName>
    <LastName></LastName>
  </FullName>
  <PhoneNumbers>
    <HomePhone></HomePhone>
    <CellPhone></CellPhone>
    <WorkPhone></WorkPhone>
    <FaxNumber></FaxNumber>
  </PhoneNumbers>
  <EmailAddress></EmailAddress>
</Customer>

Practical LearningPractical Learning: Creating XML Code

  1. Change the code as follows:
    Private Sub cmdCreateEmployee_Click()
        Dim docXMLDOM As DOMDocument
        
        If Dir("ContractWorkers.xml") = "" Then
            docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>"
        			  "<StaffMembers>" & _
                              "  <Employees>" & _
                              "    <EmployeeNumber>10000</EmployeeNumber>" & _
                              "    <FirstName>Justine</FirstName>" & _
                              "    <LastName>Sandt</LastName>" & _
                              "    <Title>Rent Management</Title>" & _
                              "  </Employees>" & _
                              "</StaffMembers>"
        
            docXMLDOM.Save "ContractWorkers.xml"
        Else
            docXMLDOM.Load "ContractWorkers.xml"
        End If
    
        Set docXMLDOM = Nothing
    End Sub
  2. Close Microsoft Visual Basic and return to Microsoft Access

The  Child Nodes of  a Node

 

Introduction to the Collection of Nodes

As mentioned already, one node can be nested inside of another. A nested node is called a child of the nesting node. This also implies that a node can have as many children as necessary, making them child nodes of the parent node. Consider our videos.xml example:

<?xml version="1.0" encoding="utf-8"?>
<videos>
    <video>
	<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director>
	<rating>R</rating>
    </video>
    <video>
	<title>Chalte Chalte</title>
	<director>Aziz Mirza</director>
	<length>145 Mins</length>
	<format>DVD</format>
    </video>
</videos>

The title and the director nodes are children of the video node. The video node is the parent of both the title and the director nodes.

To support the child nodes of a particular node, the IXMLDOMNode interface is equipped with a property named childNodes. To define this property, the MSXML library has an interface named IXMLDOMNodeList.

As you may realize, the childNodes property is a collection. This means that every member of the childNodes collection is an object of type IXMLDOMNode. This also means that if you have a group of nested elements of a nesting node, those child elements, that are of type IXMLDOMElement, are in fact members of a collection of child nodes of their parent.

As you may know already, a collection uses an index that propvides a location to each of its members. Therefore, if you have a collection of child nodes, the first element has a position of 0, the second member uses an index as 1, and so on. Using this index, you can locate an element and perform any desired operation.

The number of child nodes in a collection is represented by a property named length, which holds a numeric value. You can use it to find the number of child nodes that an element has.

Accessing a Node in a Collection

The children of a node, that is, the members of a childNodes property, or the members of an IXMLDOMNodeList collection, can be located each by an index. The first node has an index of 0, the second has an index of 1, an so on. To give you access to a node of the collection, the IXMLDOMNodeList interface is equipped with an indexed property named Item. As an example, if a node has three children, to access the third, you can apply an index of 2 to its indexed property. Here is an example:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As Object
    
    Set docXMLDOM = CreateObject("MSXML2.DOMDocument.3.0")
    
    docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _
                      "<Videos>" & _
                      "  <Video>" & _
                      "    <Title>The Distinguished Gentleman</Title>" & _
                      "    <Director>Jonathan Lynn</Director>" & _
                      "    <Length>112 Minutes</Length>" & _
                      "    <Format>DVD</Format>" & _
                      "    <Rating>R</Rating>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Title>Chalte Chalte</Title>" & _
                      "    <Director>Aziz Mirza</Director>" & _
                      "    <Format>DVD</Format>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Title>Her Alibi</Title>" & _
                      "    <Rating>PG-13</Rating>" & _
                      "  </Video>" & _
                      "</Videos>"
    
    MsgBox "Number of Main Nodes: " & CStr(docXMLDOM.childNodes.length)
    MsgBox "The root element has " & CStr(docXMLDOM.childNodes(1).childNodes.length) & " child nodes"
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

Videos

Videos

Remember that each child node is of type IXMLDOMNode, which in turn has a childNodes. This means that every time you access a child node, you get its own child nodes, if it has any. Based on this, you can call the childNodes collection of any element after accessing it by its index. Here are examples of how this can be done:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As Object
    
    Set docXMLDOM = CreateObject("MSXML2.DOMDocument.3.0")
    
    docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _
                      "<Videos>" & _
                      "  <Video>" & _
                      "    <Title>The Distinguished Gentleman</Title>" & _
                      "    <Director>Jonathan Lynn</Director>" & _
                      "    <Length>112 Minutes</Length>" & _
                      "    <Format>DVD</Format>" & _
                      "    <Rating>R</Rating>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Title>Chalte Chalte</Title>" & _
                      "    <Director>Aziz Mirza</Director>" & _
                      "    <Format>DVD</Format>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Title>Her Alibi</Title>" & _
                      "    <Rating>PG-13</Rating>" & _
                      "  </Video>" & _
                      "</Videos>"
    
    MsgBox "The root element has " & CStr(docXMLDOM.childNodes(1).childNodes.length) & " child nodes."
    MsgBox "The first child node of the root element has " & CStr(docXMLDOM.childNodes(1).childNodes(0).childNodes.length) & " child nodes."
    MsgBox "The second child node of the root element has " & CStr(docXMLDOM.childNodes(1).childNodes(1).childNodes.length) & " child nodes."
    MsgBox "The third child node of the root element has " & CStr(docXMLDOM.childNodes(1).childNodes(2).childNodes.length) & " child nodes."
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

Videos

Videos

Videos

Videos

To better manage and manipulate the nodes of a collection of nodes, you must be able to access the desired node. The IXMLDOMNode interface combined with the IXMLDOMNodeList interface provide various means of getting to a node and taking the appropriate actions.

The Parent of a Node

Not all elements have child nodes. To indicate whether an element has child nodes, the IXMLDOMNode interface has a Boolean property named hasChildNodes.

If a node is a child, to let you get its parent, the IXMLDOMNode interface has a property named parentNode, which is of type IXMLDOMNode.

The First Child Node

The child nodes of a nesting element are recognized by their index in the collection. As mentioned already, the first child node has an index of 0. For a whole XML document that has a declaration, the first child of the DOM is:

<?xml version="1.0" encoding="utf-8"?>

After identifying or locating a node, the first node that immediately follows it is referred to as its first child. To let you access the first node of an element, the IXMLDOMNode interface is equipped with a property named firstChild, which is of type IXMLDOMNode. Based on the position of any element, if it has child nodes, you can find out what the first child is. Here is an example:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As Object
    
    Set docXMLDOM = CreateObject("MSXML2.DOMDocument.3.0")
    
    docXMLDOM.loadXML "<?xml version=""1.0"" encoding=""utf-8"" ?>" & _
                      "<Videos>" & _
                      "  <Video>" & _
                      "    <Title>The Distinguished Gentleman</Title>" & _
                      "    <Director>Jonathan Lynn</Director>" & _
                      "    <Length>112 Minutes</Length>" & _
                      "    <Format>DVD</Format>" & _
                      "    <Rating>R</Rating>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Director>Aziz Mirza</Director>" & _
                      "    <Title>Chalte Chalte</Title>" & _
                      "    <Format>DVD</Format>" & _
                      "  </Video>" & _
                      "  <Video>" & _
                      "    <Rating>PG-13</Rating>" & _
                      "    <Title>Her Alibi</Title>" & _
                      "  </Video>" & _
                      "</Videos>"
    
    MsgBox "The first element from the root has the following values: " & _
	   docXMLDOM.childNodes(1).firstChild.Text
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

Video Collection

Consider the following XML document saved as videos1.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Videos>
    <Video>
	<Title>The Distinguished Gentleman</Title>
	<Director>Jonathan Lynn</Director>
	<CastMembers>
	    <Actor>Eddie Murphy</Actor>
	    <Actor>Lane Smith</Actor>
	    <Actor>Sheryl Lee Ralph</Actor>
	    <Actor>Joe Don Baker</Actor>
	    <Actor>Victoria Rowell</Actor>
	</CastMembers>
	<Length>112 Minutes</Length>
	<Format>DVD</Format>
	<Rating>R</Rating>
    </Video>
    <Video>
	<Title>Her Alibi</Title>
	<Director>Bruce Beresford</Director>
	<Length>94 Mins</Length>
	<Format>DVD</Format>
	<Rating>PG-13</Rating>
    </Video>
    <Video>
	<Title>Chalte Chalte</Title>
	<Director>Aziz Mirza</Director>
	<Length>145 Mins</Length>
	<Format>DVD</Format>
	<Rating>N/R</Rating>
    </Video>
</Videos>

Remember that every child node that is a member of a IXMLDOMNodeList collection is an object of type IXMLDOMNode and may have its own child node(s). This means that you can further get the ChildNodes collection of any node. Here is an example:

Private Sub cmdCreate_Click()
    Dim docXMLDOM  As DOMDocument
    
    Set docXMLDOM = New DOMDocument
    docXMLDOM.Load "C:\Exercises\videos1.xml"
    
    MsgBox "The first element from the root has the following values: " & docXMLDOM.childNodes(1).firstChild.Text
    MsgBox "The first child node of the first element from the root has the following value: " & docXMLDOM.childNodes(1).childNodes(0).firstChild.Text
    MsgBox "The first child node of the second element from the root has the following value: " & docXMLDOM.childNodes(1).childNodes(1).firstChild.Text
    MsgBox "The first child node of the third element from the root has the following value: " & docXMLDOM.childNodes(1).childNodes(2).firstChild.Text
    
    Set docXMLDOM = Nothing
End Sub

This would produce:

Video Collection

Video Collection

Video Collection

Video Collection

The Last Child Node

As opposed to the first child, the child node that immediately precedes the end-tag of the parent node is called the last child. To let you get the last child of a node, the IXMLDOMNode interface is equipped with a property named lastChild, which is of type IXMLDOMNode. Here is an example of accessing the last child node of the root element:

Private Sub cmdLastNode_Click()
    Dim xmlDocument As Object
    
    Set xmlDocument = CreateObject("MSXML2.DOMDocument.3.0")
    
    xmlDocument.Load "C:\Exercises\videos1.xml"

    MsgBox xmlDocument.XML
    MsgBox "The last child node of the root element is:" & vbCrLf & _
           xmlDocument.childnodes(1).lastchild.XML, _
           vbOKOnly Or vbInformation, _
           "Extensible Markup Language (XML)"
 
    Set xmlDocument = Nothing
End Sub

This would produce:

The Last Child Node

The Last Child Node

The Next Sibling of a Node

The child nodes that are nested in a parent node and share the same level are referred to as siblings. If an elment has more than one child node, a node N that comes after a node M is referred to as its next sibling (Node M is next to Node N). To let you access the next sibling of a node, the IXMLDOMNode interface is equipped with a property named nextSibling property, which is of type IXMLDOMNode. Here is an example of accessing a next sibling:

Private Sub cmdSiblingNode_Click()
    Dim xmlDocument As Object
    Dim nodSecondNode As Object
    
    Set xmlDocument = CreateObject("MSXML2.DOMDocument.3.0")
    xmlDocument.Load "C:\Exercises\videos1.xml"

    Set nodSecondNode = xmlDocument.childnodes(1).childnodes(1)
    
    MsgBox "The second child node of the root element is:" & vbCrLf & _
           nodSecondNode.XML, _
           vbOKOnly Or vbInformation, _
           "Extensible Markup Language (XML)"
 
    MsgBox "The sibling child node next to the second from the root element is:" & vbCrLf & _
           nodSecondNode.NextSibling.XML, _
           vbOKOnly Or vbInformation, _
           "Extensible Markup Language (XML)"
 
    Set xmlDocument = Nothing
End Sub

This would produce:

The Next Sibling of a Node

The Next Sibling of a Node

The Previous Sibling of a Node

Depending on its position, if one child node precedes another child node, the first child node is said to be the previous sibling of the other node. To let you access the previous sibling of a node, the IXMLDOMNode interface is equipped with a property named previousSibling. It is an IXMLDOMNode type of object. Here is an example of getting the previous sibling to a node:

Private Sub cmdSiblingNode_Click()
    Dim xmlDocument As Object
    Dim nodSecondNode As Object
    
    Set xmlDocument = CreateObject("MSXML2.DOMDocument.3.0")
    xmlDocument.Load "C:\Exercises\videos1.xml"

    Set nodSecondNode = xmlDocument.childnodes(1).childnodes(1)
 
    MsgBox "The sibling child node next to the second from the root element is:" & vbCrLf & _
           nodSecondNode.PreviousSibling.XML, _
           vbOKOnly Or vbInformation, _
           "Extensible Markup Language (XML)"
 
    Set xmlDocument = Nothing
End Sub

This would produce:

The Previous Sibling of a Node

Practical LearningPractical Learning: Ending the Lesson

  1. Close Microsoft Access
  2. When asked whether you want to save, click No
 
 
   
 

Previous Copyright © 2013 FunctionX, Inc. Next