Contents
Overview 1
The DOM View of XML Documents 2
Accessing DOM Trees 9
Transforming XML with XSL
Programmatically 22
Lab 6.1: Transforming XML Data on the
Client 31
Working with Elements and Attributes 36
Lab 6.2: Manipulating XML Data on the
Client 49
Displaying XML Data Using DOM 57
Lab 6.3: Displaying XML Data Using DOM 65
Review 72
Module 6: Manipulating
XML Data on the Client
Using DOM
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2000 Microsoft Corporation. All rights reserved.
Microsoft, PowerPoint, and Windows are either registered trademarks or trademarks of Microsoft
Corporation in the U.S.A. and/or other countries.
The names of companies, products, people, characters, and/or data mentioned herein are fictitious
and are in no way intended to represent any real individual, company, product, or event, unless
otherwise noted.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Program Manager: Steve Merrill
Instructional Designers: Sangeeta Nair (NIIT), Vijayalakshmi Narayanaswamy (NIIT)
Subject Matter Experts: Andy Olsen (QA Training), Andy Longshaw (Content Masters)
Content Lead: Janet Robinson
Graphic Artist: Scott Serna (Creative Assets)
Media Management: David Mahlmann
Media Production: Dean Connolly (Art Source), Timothy Demmon (:timebomb Media)
Editing Manager: Jennifer Linn
Editor: Dennis Rae (Wasser)
Production Manager: Miracle Davis
Print Coordinator: Marlene Lambert (Online Training Solutions, Inc)
Build Manager: Julie Challenger
Build Coordinator: Jenny Boe
Test Lead: Eric Myers
Manufacturing Manager: John Williams
Group Product Manager: Steve Elston
Module 6: Manipulating XML Data on the Client Using DOM iii
Instructor Notes
This module shows how to use the Document Object Model (DOM) to access,
manipulate, modify, extend, and transform an XML document. This is a long
module, with three labs, so you can fully expect to spend a good deal of time on
this module. Take it easy, making sure that students understand the purpose as
well as the syntax of each topic.
The module uses client-side examples to illustrate the various aspects of DOM,
but you should point out that DOM can be used equally well on the server.
Students will use DOM on the server during Module 8, “Validating XML Data
Using Schemas.”
Before beginning this module, you should ask students if they are already
familiar with another object model. (Any object model will do.) Prior exposure
to an object model makes it much easier to understand issues such as
inheritance, methods and properties, and creating objects in Microsoft
VBScript.
You should also make it clear that the module describes DOM as supported by
Microsoft. This is an extension of the current W3C standard (DOM Level 1).
The module includes features that are Microsoft extensions.
After completing this module, students will be able to:
!
List four XML Document Object Model (DOM) objects.
!
Identify the nodes of a DOM tree.
!
Retrieve information from a DOM tree.
!
Add, move, and remove nodes from a DOM tree.
!
Identify the limitations of XSL style sheet transformations.
!
Use DOM to perform a transformation between XML and HTML.
Presentation:
180 Minutes
Lab 6.1:
30 Minutes
Lab 6.2:
60 Minutes
Lab 6.3:
45 Minutes
iv Module 6: Manipulating XML Data on the Client Using DOM
Materials and Preparation
This section provides you with the required materials and preparation tasks that
you need to teach this module.
Required Materials
To teach this module, you need the following materials:
!
Microsoft PowerPoint
®
file 1905a_06.ppt
!
Module 6, “Manipulating XML Data on the Client Using DOM”
!
Lab 6.1, “Transforming XML Data on the Client”
!
Lab 6.2, “Manipulating XML Data on the Client”
!
Lab 6.3, “Displaying XML Data Using DOM”
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete the labs.
Due to the length of the answers to the labs for this course, we were unable
to include them in the Delivery Guide. Please see Appendix A or the
Student CD for the lab answers.
!
Review Microsoft’s implementation of the DOM. Go to the Web site
/> and click XML Developer’s Guide in the
Table of Contents, and then click XML DOM User Guide.
Module 6: Manipulating XML Data on the Client Using DOM v
Module Strategy
Use the following strategies to present this module:
!
The DOM View of XML Documents
This section describes how an XML parser reads an XML document into an
in-memory tree. Each item in the XML document is represented by a Node
in the tree.
Emphasize that there is a Document node at the top of the tree. This is not
the root element of the XML document — the root element is a child of the
Document node.
Be careful how you describe the inheritance relationship between Node and
Document/Element/Attr, and so on. Some students get confused between
the hierarchy of Node instances (that is, the object tree) and the inheritance
hierarchy of Node classes.
!
Accessing DOM Trees
In this section, students learn about basic navigation of a DOM tree. The
section shows how to attach the Document node to an XML data island, or
alternatively how to load an external XML document into an XMLDOM
object.
The section then describes how to navigate up, down, and across the DOM
tree. The section also describes the properties that are common to all types
of nodes — nodeName, nodeType, and nodeValue.
!
Transforming XML with XSL Programmatically
Style sheets were first introduced in Module 2, “Overview of XML
Technologies,” then again in more detail in Module 4, “Displaying an XML
Document Using XSL.”
This section shows how to apply a style sheet to an XML document
dynamically, so that the choice of style sheet can be made at run time.
!
Lab 6.1: Transforming XML Data on the Client
This lab asks students to apply a style sheet to the “book” data island in
order to transform it into a suitable format to add to the “order” data island.
The style sheet that performs the transformation has already been written —
students can use this style sheet as is, without modification.
!
Working with Elements and Attributes
This section extends the basic navigation capabilities introduced at the
beginning of the module, to show how to add, remove, and replace elements
and attributes in an XML document. The selectNodes and selectSingleNode
methods sometimes cause confusion, so deal carefully with these topics.
Another potential difficulty is the fact that an Element node does not
contain the value for the element — this is held in a child Text node.
!
Lab 6.2: Manipulating XML Data on the Client
This lab asks students to use DOM to add more details to the “order” data
island. There are many opportunities for students to go astray with the
syntax, so keep a close eye to make sure students don’t lose time with
simple syntax errors.
vi Module 6: Manipulating XML Data on the Client Using DOM
!
Displaying XML Data Using DOM
This is the final section of a long module, so you need to be sensitive to the
students’ ability to absorb new information. The concept of this section is
simple: DOM lets you build an HTML string dynamically and display the
string in a <DIV> or similar element.
This section is quite short and straightforward. Do not expect to spend as
much time here as in the other sections.
!
Lab 6.3: Displaying XML Data Using DOM
Students build an HTML table from the “order” data island. Each order is
represented as a different row in the table. This part of the lab is relatively
simple, so students should be able to cope quite easily.
Module 6: Manipulating XML Data on the Client Using DOM 1
#
##
#
Overview
!
The DOM View of XML Documents
!
Accessing DOM Trees
!
Transforming XML with XSL Programmatically
!
Lab 6.1: Transforming XML Data on the Client
!
Working with Elements and Attributes
!
Lab 6.2: Manipulating XML Data on the Client
!
Displaying XML Data Using DOM
!
Lab 6.3: Displaying XML Data Using DOM
!
Review
In Module 2, “Overview of XML Technologies,” you learned about the concept
of using the Document Object Model (DOM) to access an XML document
programmatically. In this module, you will learn the details of DOM
programming.
With the DOM, you can access an XML data island or load a new XML
document into memory from a file. Once the XML tree is in memory, you can
use the DOM objects, properties, and methods to parse, navigate, and
manipulate the XML document. You can also perform intelligent searches on
the XML data with DOM.
After completing this module, you will be able to:
!
List four XML DOM objects.
!
Identify the nodes of a DOM tree.
!
Retrieve information from a DOM tree.
!
Add, move, and remove nodes from a DOM tree.
!
Identify the limitations of XSL style sheet transformations.
!
Use DOM to perform a transformation between XML and HTML.
Slide Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
more about the Document
Object Model (DOM) and
how to dynamically load a
document and manipulate
DOM trees.
2 Module 6: Manipulating XML Data on the Client Using DOM
#
##
#
The DOM View of XML Documents
!
Parsing XML Data
!
The DOM Tree Structure
!
Everything Is a Node
!
W3C Standard vs. Microsoft’s Implementation
In this section, you will learn about XML parsers and how they parse an XML
document into a tree structure in memory. You will also learn about the XML
Document Object Model (DOM), which allows XML data to be manipulated
programmatically.
For more information on Microsoft’s implementation of the DOM, go to
/>, click XML Developer’s Guide in the Table of
Contents, and then click XML DOM User Guide.
Slide Objective
To provide an overview of
the topics in this section
Lead-in
The XML parser creates a
tree structure to hold the
data in an XML document.
Trees are very flexible, and
the DOM is essentially a set
of interfaces that provide
methods and properties for
manipulating these trees.
Module 6: Manipulating XML Data on the Client Using DOM 3
Parsing XML Data
<?xml version="1.0"?>
<?xml-stylesheet href="…" type="text/xsl"?>
<booklist>
<book>
<title>Sushi, Anyone?</title>
<isbn>72-80081-024</isbn>
<publisher>New Moon Books</publisher>
<price>14.99</price>
<details>…</details>
<author>Charlotte M. Cooper</author>
<author>Yoshi Nagase</author>
</book>
…
</booklist>
<?xml version="1.0"?>
<?xml-stylesheet href="…" type="text/xsl"?>
<booklist>
<book>
<title>Sushi, Anyone?</title>
<isbn>72-80081-024</isbn>
<publisher>New Moon Books</publisher>
<price>14.99</price>
<details>…</details>
<author>Charlotte M. Cooper</author>
<author>Yoshi Nagase</author>
</book>
…
</booklist>
!
XML parser reads an XML document and represents the
data as a tree structure in memory
The XML parser is part of Microsoft
®
Internet Explorer 5. The parser takes an
XML document, breaks the data into tokens according to certain rules, and
creates a new interpretation of the data as a tree structure in memory.
The parser requires a well-formed document as its input, and will reject any
document that does not conform to the basic rules of XML syntax.
Some parsers also perform validation checks on XML documents. A validating
parser will check the XML document against an attached XML schema or
DTD. The parser in Internet Explorer 5 is capable of performing validation
checks, but does not do so by default.
In addition to the parser provided in Internet Explorer 5, Microsoft also
provides an XML validation tool named Xmlint.exe, which can be used to
verify that an XML document is well formed. Xmlint.exe can be downloaded
from the following Web site:
/>.
The following is an example of how you can use Xmlint.exe from the command
line:
xmlint –w c:\myxmldata\*.xml
This command checks all the XML documents in the folder C:\myxmldata for
well-formedness. The “-w” flag indicates that the well-formedness check is
required.
Slide Objective
To describe the role of the
XML parser.
Lead-in
The XML parser is a tool
that transforms XML
documents into
programmable tree
structures.
Note
4 Module 6: Manipulating XML Data on the Client Using DOM
The DOM Tree Structure
!
A tree structure reflects the hierarchy
of data in an XML document
!
DOM defines objects to represent
nodes in the tree
$
A Document object contains the
entire XML tree
$
Other objects represent elements,
attributes, etc.
Document
Text
Text
Element
Attr
Text
Element
Element
Document
Element
The XML parser creates a tree to represent the data — parsing instructions,
elements, attributes, and so on — in an XML document. Items in the tree are
called nodes. The XML DOM defines a set of objects that allow the nodes in
the tree to be accessed or modified.
Document object
The top node (also known as the root node) of the tree is a Document object.
This node contains the entire contents of the XML document, including the
processing instructions, the root element, and all its child elements. The
Document object has properties and methods for creating new nodes (elements
and attributes) and adding them to the tree, and for manipulating the XML
document as a whole.
Element and Attr objects
Other nodes in the tree represent parts of the XML document. The nodes are
arranged in a hierarchy that reflects the structure of the XML document itself.
There are different types of DOM objects for manipulating nodes that represent
different parts of a document. For example, the Element object contains
methods and properties pertaining to XML elements. Likewise, the Attr object
contains methods and properties pertaining to XML attributes. (The W3C
named the object Attr rather than Attribute to avoid clashing with existing
Interface Definition Languages.)
Methods are available for inserting or removing a child node from any node in
the tree. This enables the underlying tree structure to be changed
programmatically.
Slide Objective
To discuss the reasons why
a tree structure is
appropriate for representing
XML data, and to introduce
the main DOM objects.
Lead-in
When an XML document is
loaded into a parser, the
parser creates a tree
structure to represent the
data. A tree is an
appropriate structure for
representing XML data.
Module 6: Manipulating XML Data on the Client Using DOM 5
Text object
The Text node represents the text content of an element or attribute. A text
node cannot have any child nodes. The Text node can appear as the child node
of the Element and Attribute nodes.
Collections
The DOM tree contains several collections. For example, each node potentially
has a collection of child nodes. The collections have methods and properties
that allow you to traverse the nodes sequentially. In all collections, numbering
starts at 0.
6 Module 6: Manipulating XML Data on the Client Using DOM
Everything Is a Node
Document Element Attr Text
Node
!
The Node object defines methods and properties
$
firstChild, lastChild, previousSibling, nextSibling
$
nodeValue, nodeType, nodeName
Every ‘branch’ of the DOM tree is a Node object. It does not matter whether
the node is an element, an attribute, a simple piece of text, or the document
itself — the DOM defines a simple inheritance hierarchy with the Node object
as the root.
The Node object defines methods and properties that are common to all types
of nodes:
!
The firstChild, lastChild, nextSibling, and previousSibling methods
provide navigational support. For example, you can use these methods to
iterate through all of the child elements of an element.
!
The nodeValue, nodeType, and nodeName properties allow you to query
any node in the DOM tree and determine its value, type (for example, an
element or an attribute), and name (for example, the name of an element or
an attribute).
There are additional properties and methods, depending on what type of node
you are dealing with.
The nodeType property distinguishes one node type from another, as shown in
the following table.
Node NodeType property Value
Document NODE_DOCUMENT 9
Element NODE_ELEMENT 1
Attr NODE_ATTRIBUTE 2
Text NODE_TEXT 3
Slide Objective
To introduce the node types
and Node object methods
and properties.
Lead-in
Earlier we saw that the
parser creates a tree
structure in memory. Every
data item in the tree is a
node.
Module 6: Manipulating XML Data on the Client Using DOM 7
For example, in the following XML data island, the entire dsoOrder data island
is a Document node, the <order> and <orderitem> elements are Element
nodes, the title and isbn attributes are Attr nodes, and the values “Sushi,
Anyone?” and “72-80081-024” are Text nodes.
<XML ID="dsoOrder">
<?XML version="1.0"?>
<order>
<orderitem title="Sushi, Anyone?" isbn="72-80081-024">
</orderitem>
</order>
</XML>
8 Module 6: Manipulating XML Data on the Client Using DOM
W3C Standard vs. Microsoft’s Implementation
!
DOM levels
$
Level 1 — As described in this module
$
Level 2 — Level 1 + namespaces + style sheets
!
Microsoft’s implementation
$
All of Level 1
$
Much of Level 2
$
Additional features
DOM level 2
Internet
Explorer 5
DOM level 1
The DOM levels specified by the W3C are well defined and documented. Level
1 is fixed and has formed the basis for most of the discussions in this module.
Level 2 adds support for XML namespaces and style sheets.
DOM Level 2 is rapidly approaching “Recommendation” status. More
details can be found at the Web site />.
Microsoft’s implementation
The Microsoft implementation of DOM supports DOM Level 1 in its entirety,
and much of Level 2. The Microsoft DOM also implements a small number of
additional interfaces, methods, and properties.
For more information on Microsoft’s implementation of the DOM, go to
/>, click XML Developer’s Guide in the Table of
Contents, and then click XML DOM User Guide.
In this module, you will learn about Level 1 objects. Some of the key
Microsoft extensions are also introduced.
Slide Objective
To discuss Microsoft’s
extensions to DOM.
Lead-in
Microsoft has implemented
several interfaces beyond
the standards specified by
the WC3.
Note
Note
Module 6: Manipulating XML Data on the Client Using DOM 9
#
##
#
Accessing DOM Trees
!
Accessing XML Data
!
Accessing the Root Element
!
Navigating Elements in the DOM Tree
!
Navigating Node Collections
!
Retrieving Node Content
!
Demonstration: Retrieving Node Content
This section introduces the DOM, its main objects, and some of their methods
and properties. You will learn how to retrieve data from an XML document
programmatically, and how to navigate the tree in order to access various data
items in a document.
Slide Objective
To provide an overview of
the topics in this section.
Lead-in
So far you have looked at
the general concepts of
DOM. Next you will be
shown some specific
examples of accessing
individual data items from
the DOM tree.
10 Module 6: Manipulating XML Data on the Client Using DOM
Accessing XML Data
!
Access an XML data island
!
Access an external XML document
<XML ID="dsoDetails" src="Books.xml"></XML>
Set doc = dsoDetails.XMLDocument
<XML ID="dsoDetails" src="Books.xml"></XML>
Set doc = dsoDetails.XMLDocument
Set doc = CreateObject("Microsoft.XMLDOM")
doc.async = False
doc.load "Books.xml"
Set doc = CreateObject("Microsoft.XMLDOM")
doc.async = False
doc.load "Books.xml"
Using the DOM starts with creating the Document object, either from an XML
data island or from an external XML document file.
Accessing a data island
You can access an XML data island by using the ID attribute of the data island.
The XMLDocument property of the data island provides a reference to the
Document object.
For example, the following code defines an XML data island and then obtains
the Document object by using the ID of the data island:
<XML ID="dsoDetails" src="Books.xml"></XML>
Set doc = dsoDetails.XMLDocument
The doc variable can now be used to access all of the nodes in the XML tree.
Accessing an external XML document
Microsoft DOM includes a number of extensions to the W3C Level 1 DOM, to
allow you to dynamically load an XML document into a DOM tree.
Create an XML DOM object
The first step is to create an XML DOM object by using the CreateObject
method of VBScript as follows:
Set doc = CreateObject("Microsoft.XMLDOM")
Slide Objective
To access a DOM document
and its underlying data from
an XML Data Source Object
(DSO) or external file.
Lead-in
Before you can access the
nodes in the XML
document, you must
programmatically retrieve
the DOM document
interface from a DSO or an
XML document file.
Module 6: Manipulating XML Data on the Client Using DOM 11
Set the async property
Next, set the async property to False to indicate that the XML document should
not to be loaded asynchronously. The default value of the async property is
True.
You can then use the readyState property to check the status of the download.
You can also attach an onreadystatechange event handler to be notified when
the ready state changes so that you know when the download is complete.
For more information on the async property, see the XML DOM Reference at
.
The following is an example of setting the async property:
doc.async = False
Load the XML document
Finally, load the XML document into the XML DOM object by using the load
method, which takes the URL of the XML document you wish to load as its
single parameter. The following example loads Books.xml into an XML DOM
object:
doc.load "Books.xml"
The XML DOM object also has a loadXML method for loading an XML string
into the DOM tree. This method takes the XML string to be loaded as its single
parameter. The following example loads a simple XML string representing an
empty booklist:
doc.loadXML "<?xml version='1.0'?><booklist></booklist>"
Delivery Tip
Remember to tell students
that setting the async
property to True does not
work in the current release
of Internet Explorer 5.0.
12 Module 6: Manipulating XML Data on the Client Using DOM
Accessing the Root Element
!
To access the root element, use the documentElement
property of the Document node
!
To access the XML data in any node,
use the xml property
$
For example, obtain the XML data for the root node
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
MsgBox rootNode.xml
MsgBox rootNode.xml
Once you have a reference to the Document object of a DOM tree, you can
access the root node of the document with the documentElement property as
follows:
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
Viewing the XML data
Microsoft DOM defines an xml property in the Node object. This property can
be used on any node to retrieve the XML data contained in that portion of the
DOM tree.
For example, the following code displays the entire XML document, including
any processing instructions:
MsgBox dsoDetails.XMLDocument.xml
The next example displays the XML from the root node on down:
MsgBox dsoDetails.XMLDocument.documentElement.xml
Slide Objective
To access the root element
from any node in the tree.
Lead-in
The root element of the
DOM tree is accessed with
the documentElement
property.
Delivery Tip
The xml property is a
Microsoft extension.
Module 6: Manipulating XML Data on the Client Using DOM 13
Navigating Elements in the DOM Tree
theNode
theNode.nextSibling
theNode.parentNode
theNode.ownerDocument
theNode.parentNode.childNodes(0)
!
DOM includes properties for navigating the tree
theNode.parentNode.lastChild
After the DOM tree has been generated, you can examine it by using the
appropriate Node object properties. This can be done by using client-side script.
When you establish a reference to any node in the tree, it is possible to examine
any neighboring or related nodes.
Consider the preceding slide. This tree can be navigated by accessing various
nodes through the following properties:
!
ownerDocument returns a reference to the top-level Document node.
It is possible to access the Document node from any other node in the DOM
tree by using the ownerDocument property as follows:
Set doc = thenode.ownerDocument
!
parentNode returns a reference to a node’s parent node.
!
childNodes returns a collection of child nodes. The collection is zero-based.
The first child node is childNodes(0), the second child node is
childNodes(1), and so on.
!
nextSibling and previousSibling reference the next and previous nodes in a
collection of child nodes.
!
firstChild and lastChild reference the first and last child nodes.
Slide Objective
To introduce methods and
properties used to navigate
within the DOM tree.
Lead-in
Once the DOM tree has
been generated, you can
find elements by using Node
properties.
Delivery Tip
The slide is animated to
progressively display node
references in the tree on
successive mouse clicks.
Click the slide to expose
each of the following items
in sequence:
1. theNode
2. theNode.ownerDocument
3. theNode.parentNode
4. theNode.parentNode.
childNodes(0)
5. theNode.nextSibling
6. theNode.parentNode.
lastChild
14 Module 6: Manipulating XML Data on the Client Using DOM
For example, let’s look at the following XML document:
<xml id="dsoBooks">
<?xml version="1.0"?>
<booklist>
<book>
<title>The Gourmet Microwave</title>
<price>9.95</price>
</book>
<book>
<title>Sushi, Anyone?</title>
<price>14.99</price>
</book>
<book>
<title>Straight Talk About Computers</title>
<price>19.99</price>
</book>
</booklist>
</xml>
The following code declares a variable named theNode and sets it to the second
<book> element, Sushi Anyone?.
Set theNode = _
dsoBooks.XMLDocument.documentElement.childNodes(1)
The following examples show how to navigate the DOM tree relative to this
node:
!
theNode.ownerDocument refers to the XML document itself.
!
theNode.previousSibling refers to the first <book> element, The Gourmet
Microwave.
!
theNode.nextSibling refers to the third <book> element, Straight Talk
About Computers.
!
theNode.parentNode refers to the <booklist> element.
!
theNode.parentNode.firstChild refers to the first <book> element, The
Gourmet Microwave.
!
theNode.parentNode.lastChild refers to the last <book> element, Straight
Talk About Computers.
!
theNode.childNodes refers to the collection of child elements of the current
node, for example, the <title> and <price> elements of Sushi Anyone?.
!
theNode.childNodes(0) refers to first child element of the current node, for
example, the <title> element of the Sushi Anyone?.
Module 6: Manipulating XML Data on the Client Using DOM 15
Navigating Node Collections
!
childNodes returns a NodeList collection
$
Zero-based collection of nodes
!
Use a loop to navigate through the collection
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
For Each child in rootNode.childNodes
'Access data in child node
Next
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
For Each child in rootNode.childNodes
'Access data in child node
Next
The childNodes property returns a NodeList object. NodeList is a zero-based
collection of nodes, and can be iterated through to access each item in the
collection.
The NodeList object is typically used to navigate through elements by using an
indexed loop. For example, the following code will iterate through all child
elements of the root element:
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
For Each child in rootNode.childNodes
'Access data in child node
Next
You can also use the item property of the NodeList collection to access specific
items in the collection. The following example is equivalent to the preceding
one, and accesses each child element of the root element:
Set doc = dsoDetails.XMLDocument
Set rootNode = doc.documentElement
Set children = rootNode.childNodes
For i = 0 To children.length - 1
'Access data in children.item(i)
Next
Slide Objective
To use the collection objects
in DOM.
Lead-in
DOM collections are
returned by several methods
and properties. These
collections contain nodes
that hold logically connected
data. Navigating through
collections is a very
common activity.
16 Module 6: Manipulating XML Data on the Client Using DOM
The NodeList collection has a length property that indicates the number of
nodes in the collection.
The NodeList object is also returned from the getElementsByTagName
method, which returns a collection of all elements with a specific name. The
getElementsByTagName method is introduced later in this section.
Note
Module 6: Manipulating XML Data on the Client Using DOM 17
Retrieving Node Content
Set doc = dsoDetails.XMLDocument
MsgBox doc.nodeType
Set rootNode = doc.documentElement
MsgBox rootNode.nodeType
MsgBox rootNode.nodeName
Set price = rootNode.firstChild.childNodes(1)
Set priceValue = price.firstChild
MsgBox priceValue.nodeValue
Set doc = dsoDetails.XMLDocument
MsgBox doc.nodeType
Set rootNode = doc.documentElement
MsgBox rootNode.nodeType
MsgBox rootNode.nodeName
Set price = rootNode.firstChild.childNodes(1)
Set priceValue = price.firstChild
MsgBox priceValue.nodeValue
9
1
booklist
9.95
Once a node has been referenced, its details can be accessed and manipulated
by using specific properties. The W3C-standard Node object defines three
properties, which can be used to find out information about any type of node:
!
nodeType is the type of the node, expressed as a number. For example, the
nodeType of the document is 9, the nodeType of an element is 1, and the
nodeType for an attribute is 2.
!
nodeName is the name of the node, such as the name of an element or an
attribute.
!
nodeValue is value of the node, such as the value of a text node or an
attribute.
Slide Objective
To access the data in the
nodes of the DOM tree.
Lead-in
Once you have navigated to
the node you want, use
properties to retrieve data
from that node.
Delivery Tip
There is a Microsoft
extension to the DOM,
nodeTypeString, that returns
the node type in a string
format.
18 Module 6: Manipulating XML Data on the Client Using DOM
Example of using standard node properties
Let’s look at the following XML document, and see how Node properties can
be used to find out information about the document:
<xml id="dsoDetails">
<?xml version="1.0"?>
<booklist>
<book>
<title>The Gourmet Microwave</title>
<price>9.95</price>
</book>
<book>
<title>Sushi, Anyone?</title>
<price>14.99</price>
</book>
</booklist>
</xml>
The nodeType property
The nodeType property of a node returns the type of node. For example, the
following script accesses the XML data island and then retrieves the nodeType
of that node. The message box displays the value 9, indicating a node of the
type NODE_DOCUMENT.
Set doc = dsoDetails.XMLDocument
MsgBox doc.nodeType
The following script then accesses the documentElement property of the XML
data island, which returns the root element, for example, the <booklist>
element. The nodeType of this node is retrieved, and the message box displays
1 as the retrieved value. The value 1 indicates a node of the type
NODE_ELEMENT.
Set rootNode = doc.documentElement
MsgBox rootNode.nodeType
The nodeName property
The nodeName property of a node returns the identifier of the node. For
example, the nodeName of an element is the name of the element without the
angular brackets <>. Likewise, the nodeName of an attribute is the name of the
attribute.
The following script displays the identifier of the root element, which is
“booklist”:
MsgBox rootNode.nodeName
Module 6: Manipulating XML Data on the Client Using DOM 19
The nodeValue property
The nodeValue property of a node contains the value of a node. The nodeValue
of an attribute contains the value of the attribute. However, the nodeValue of an
element is null — the text content of an element is held in a child node of the
type NODE_TEXT.
For example, the following script navigates to the <title> element of the first
book, that is, The Gourmet Microwave. It then gets the Text node of that
element and outputs the nodeValue property, which is the string “The Gourmet
Microwave”.
Set title = rootNode.firstChild.childNodes(0) 'The <title>
Set titleValue = title.firstChild 'Its Text node
MsgBox titleValue.nodeValue
Microsoft extensions to the node object
Microsoft defines a number of additional properties on the Node object that
provide more information about nodes in the DOM tree. Here are three useful
properties:
!
nodeTypeString is the type of the node, expressed as a string. For example,
the nodeTypeString of the document is “document”, the nodeTypeString of
an element is “element”, and the nodeTypeString of an attribute is
“attribute”.
!
text returns the textual content of the node and all its descendants.
!
xml returns the XML of the node and all its descendants.
Example of using Microsoft-specific node properties
Using the same XML document as before, let’s consider how the Microsoft-
specific node properties can be used.
The nodeTypeString property
The following script accesses the XML data island and then retrieves the
nodeTypeString of that node. The message box displays “document”,
indicating a node of the type NODE_DOCUMENT.
Set doc = dsoDetails.XMLDocument
MsgBox doc.nodeTypeString
The following script then accesses the documentElement property of the XML
data island, which returns the root element. The nodeTypeString of this node is
“element”, indicating a node of the type NODE_ELEMENT.
Set rootNode = doc.documentElement
MsgBox rootNode.nodeTypeString