1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Module 6: Manipulating XML Data on the Client Using DOM doc

80 507 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Manipulating XML Data on the Client Using DOM
Tác giả Steve Merrill, Sangeeta Nair, Vijayalakshmi Narayanaswamy, Andy Olsen, Andy Longshaw, Janet Robinson, Scott Serna, David Mahlmann, Dean Connolly, Timothy Demmon, Jennifer Linn, Dennis Rae, Miracle Davis, Marlene Lambert, Julie Challenger, Jenny Boe, Eric Myers, John Williams, Steve Elston
Người hướng dẫn Dennis Rae (Editor)
Trường học Microsoft Corporation
Thể loại module
Năm xuất bản 2000
Thành phố Redmond
Định dạng
Số trang 80
Dung lượng 1,09 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Node NodeType property Value Document NODE_DOCUMENT 9 Element NODE_ELEMENT 1 Text NODE_TEXT 3 Slide Objective To introduce the node types and Node object methods and properties.. For

Trang 1

Contents

Overview 1

The DOM View of XML Documents 2

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

Trang 2

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

Trang 3

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

Trang 4

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 http://msdn.microsoft.com/xml and click XML Developer’s Guide in the Table of Contents, and then click XML DOM User Guide

Trang 5

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

Trang 6

! 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

Trang 7

# 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

In this module, you will learn

more about the Document

Object Model (DOM) and

how to dynamically load a

document and manipulate

DOM trees

Trang 8

# 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 http://msdn.microsoft.com/xml, 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

Trang 9

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:

http://msdn.microsoft.com/downloads/tools/xmlint/xmlint.asp 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

Trang 10

The DOM Tree Structure

! A tree structure reflects the hierarchy

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

Trang 12

Everything Is a Node

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

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

Trang 13

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

Trang 14

W3C Standard vs Microsoft’s Implementation

! DOM levels

$ Level 1 — As described in this module

$ Level 2 — Level 1 + namespaces + style sheets

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 http://www.w3.org/DOM/

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 http://msdn.microsoft.com/xml, 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

Trang 15

# 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

Trang 16

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

the DOM document

interface from a DSO or an

XML document file

Trang 17

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

http://msdn.microsoft.com

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

Trang 18

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.XMLDocumentSet rootNode = doc.documentElement

Set doc = dsoDetails.XMLDocumentSet 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

Trang 19

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

Trang 20

For example, let’s look at the following XML document:

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?

Trang 21

Navigating Node Collections

! childNodes returns a NodeList collection

$ Zero-based collection of nodes

! Use a loop to navigate through the collection

Set doc = dsoDetails.XMLDocumentSet rootNode = doc.documentElement

For Each child in rootNode.childNodes'Access data in child node

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

Trang 22

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

Trang 23

Retrieving Node Content

Set doc = dsoDetails.XMLDocumentMsgBox doc.nodeType

Set rootNode = doc.documentElementMsgBox rootNode.nodeType

MsgBox rootNode.nodeNameSet 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

Trang 24

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:

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

Trang 25

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 specific node properties can be used

Microsoft-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

Trang 26

The text property

The following script accesses the root element, and then retrieves the text property of that node This property returns the entire text content of the root

element and all its descendants The resulting message box is shown following the script

MsgBox rootNode.text

The xml property

The following script accesses the root element and then retrieves the xml

property of that node This property returns the entire XML of the root element and all its descendants The resulting message box is shown following the script

MsgBox rootNode.xml

Trang 27

Demonstration: Retrieving Node Content

In this demonstration, you will learn how to write script that accesses an XML data island using DOM The demonstration uses the following code:

Sub Fill_OnClick() 'Display the name of the root node in a LABEL Dim doc, rootNode, firstbook, price, content Set doc = dsoDetails.XMLDocument

Set rootNode = doc.documentElement lblRoot.InsertAdjacentText "BeforeEnd", rootNode.nodeName 'Get the price of the first <book> element and display Set firstbook = rootNode.firstChild 'first <book> element Set price = firstbook.childNodes(3) '<price> element Set content = price.firstChild 'content of <price> lblPrice.InsertAdjacentText "BeforeEnd", content.nodeValue End Sub

Slide Objective

To demonstrate how to

open an XML document and

retrieve nodes from the

document

Lead-in

In this demonstration, you

will see how to reference an

XML data island and access

the nodes of the DOM tree

to the XML data island and

note the ID

2 Locate the LABEL

elements at the bottom of

the page and note their IDs

3 Point out that the

BUTTON element has an

on-click event procedure

that reads information from

the data island and displays

it in the labels

4 View the page in the

browser

Trang 28

# Transforming XML with XSL Programmatically

! Overview of Transforming Programmatically

! Transforming on the Client

! Transforming on the Server

! Handling Errors

! Demonstration: Transforming an XML Document

In Module 4, “Displaying an XML Document Using XSL,” you learned how to create an XSL style sheet to transform an XML document statically into another format

In this section, you will learn how to achieve dynamic transformation You will

see how to load an XSL style sheet into an XMLDOM object at run time, and

use the style sheet to transform an XML document into another DOM tree or an XML string

Slide Objective

To introduce the topics in

this section

Lead-in

An XSL style sheet can be

loaded into an XMLDOM

object in order to

dynamically transform an

XML document into another

format

Trang 29

Overview of Transforming Programmatically

XSL style sheet

+

XML DOM tree

New DOM tree

! Transforms the XML document dynamically

$ Into a different DOM tree, or a string

DOM allows an XSL style sheet to be attached to an XML document dynamically The style sheet can transform the XML data at run time, without needing to transform the data manually in script

The technique relies on the fact that an XSL style sheet is itself an XML

document, and can therefore be loaded into an XMLDOM object

Once you have loaded the style sheet into an XMLDOM object, you can use it

in conjunction with the transformNodeToObject or transformNode methods

Both of these methods apply the style sheet to an XML document in order to transform it according to the rules specified in the style sheet:

! The transformNodeToObject method performs the transformation and

writes the output into another DOM tree

! The transformNode method performs the transformation and writes the

output into a string

The style sheet can

transform the XML data

dynamically, without

needing to transform the

data manually in script

Trang 30

Transforming on the Client

! Load the XSL style sheet into a DOM object

! The transformNodeToObject method writes the transformed node into a new node

! The transformNode method writes the transformed node into a string

Set stylesheet = CreateObject("Microsoft.XMLDOM")stylesheet.async = False

Note that you can transform any node by using these methods This means that you can transform only a part of a DOM tree if desired

Transforming XML using transformNodeToObject

The transformNodeToObject method takes two parameters:

! The first parameter is the style sheet to be used for the transformation The

style sheet document can be loaded into an XMLDOM object as follows:

Set stylesheet = CreateObject("Microsoft.XMLDOM") stylesheet.async = False

stylesheet.load "TransformDetails.xsl"

! The second parameter is the node that will hold the XML data after it has

been transformed A new XMLDOM object can be created for holding the

Tell students that

targetNode is not a node but

the target document

Trang 31

The transformNodeToObject method can be used as shown in the following

code, where a source node named srcNode is transformed into a target document named targetNode The style sheet specifies the transformation required

srcNode.transformNodeToObject stylesheet, targetNode

Transforming XML using transformNode

The transformNode method takes as a single parameter the style sheet to be

used for the transformation The style sheet can be loaded as you saw earlier

The transformNode method can be used as shown in the following code,

where a source node named srcNode is transformed into a string variable named str:

str = srcNode.transformNode(stylesheet)

Example of transforming an XML document at the client

Let’s consider an example to illustrate the usefulness of dynamic transformation Suppose there is an XML data island at the client that contains the following information about books in a bookstore:

Trang 32

The user wants the data to be displayed in an HTML table, and wants to be able

to sort the table by clicking the table column headings

This table may be defined as follows in the HTML page:

<TABLE DATASRC="#dsoBooks" BORDER="1" WIDTH="80%">

<THEAD STYLE="cursor:hand; background-color:wheat">

<TR>

<TD onclick="mySort('title')" width="50%">Title</TH> <TD onclick="mySort('author')" width="25%">Author</TH> <TD onclick="mySort('publisher')" width="25%">Publisher</TH>

Note that the table is bound to the XML data island, dsoBooks Also notice that

the table heading <THEAD> defines the cursor:hand style, so that the mouse

changes when placed over the table heading

The table heading has three columns for the title, author, and publisher,

respectively Each table heading has an onclick event procedure that calls the

VBScript procedure named mySort, passing an appropriate parameter The parameter indicates which column in the table to sort

Trang 33

Before looking at the mySort procedure, let’s consider how to write a style sheet to perform the sorting Imagine the style sheet is named MyBookSort.xsl The following version of MyBookSort.xsl sorts the XML book data by title:

End Sub

</SCRIPT>

The procedure begins by loading the MyBookSort.xsl style sheet into a DOM

tree We then locate the order-by attribute in the style sheet, and change this

attribute to cause sorting on the correct column (as specified by the sortCol parameter)

Next, the procedure applies the style sheet to the XML data island in order to perform the sorting operation, and then loads the sorted XML data into dsoBooks The <TABLE> that is bound to dsoBooks is automatically refreshed

to display the sorted data

Trang 34

Transforming on the Server

! Use transformNodeToObject or transformNode as before

! Or use transformNodeToObject to write the new node directly to the Response object

srcNode.transformNodeToObject stylesheet, Response

Set targetNode = CreateObject("Microsoft.XMLDOM")srcNode.transformNodeToObject stylesheet, targetNode

The transformNodeToObject and transformNode methods can be used at the

server in exactly the same way as at the client, to cause an XML document to be transformed dynamically at the server

This allows the server to choose which style sheet is appropriate at run time, perhaps depending on what type of browser is available at the client The server can apply a different style sheet for different browsers in order to target the specific capabilities of each browser

When using the transformNodeToObject method to transform an XML document into another DOM tree at the server, you can specify the Response

object as the recipient for the transformation:

srcNode.transformNodeToObject stylesheet, Response This causes the transformed XML data to be written directly to the client

You can also dynamically

apply a style sheet to an

XML document at the

server

Trang 35

Handling Errors

! The Document object has a parseError property

$ Returns a reference to a ParseError object

! The ParseError object detects errors in a document

If srcNode.parseError.errorCode <> 0 Then'return an error message with information 'from the parseError object

End If

If srcNode.parseError.errorCode <> 0 Then'return an error message with information 'from the parseError object

End If

In the Microsoft DOM, the Document object has an additional property named parseError that returns a reference to a ParseError object

Detecting parse errors with the ParseError object

The ParseError object contains a number of properties that describe any errors

that may occur as an XML document is transformed The following table

describes the properties of the ParseError object

Property Description errorCode The numeric error code for the parse error

filepos The absolute character position in the XML document where the parse

error occurred

line The line number in the XML document where the parse error occurred

linepos The character position on the line where the parse error occurred

reason A textual description of the reason for the parse error

srcText The full source text for the line in the XML document where the parse

error occurred If the parse error is more general than a specific line, this property returns an empty string

url The URL of the most recent XML document that contained a parse error

Slide Objective

To describe how to detect

transformation errors and

obtain information about

such errors

Lead-in

The Microsoft DOM includes

extensions that allow you to

test the outcome of a

transformation and obtain

detailed information about

any errors

Trang 36

Demonstration: Transforming an XML Document

In this demonstration, you will see how to write a script to transform a <book> node into an <orderitem> node by using an XSL style sheet The

demonstration uses the following script code:

'Create an XML DOM object, and load an XSL stylesheet into it Set stylesheet = CreateObject("Microsoft.XMLDOM")

stylesheet.async = False stylesheet.load "TransformBookDetails.xsl"

'Create an XML DOM object to contain the transformed node Set targetNode = CreateObject("Microsoft.XMLDOM")

'Transform the book node using the stylesheet doc.transformNodeToObject stylesheet, targetNode MsgBox targetNode.xml

In this demonstration, you

will be shown how to

transform the data from an

XML island by using an XSL

style sheet applied in DOM

script

Delivery Tip

1 Open the file

BookOrder.htm in the folder

subroutine that transforms

the XML data through the

TransformBookDetails.xsl

style sheet

3 View the page in the

browser Click the Data

button The first message

box displays the original

form of the XML data, the

second message box is the

same data in a transformed

Trang 37

Lab 6.1: Transforming XML Data on the Client

Objectives

After completing this lab, you will be able to:

! Transform an XML data island into a different XML structure

Prerequisites

Before working on this lab, you must have:

! Basic knowledge of client-side scripting with Microsoft VBScript

! Familiarity with using object models in VBScript

Scenario

In this lab, you will write client-side VBScript to transform the XML data island in Details.asp into a different XML format by using the XML Document Object Model (DOM)

Starter and solution files

There are starter and solution files associated with this lab The starter files are

in the folder <install folder>\Labs\Lab06.1\Starter and the solution files for this lab are in the folder <install folder>\Labs\Lab06.1\Solution

Estimated time to complete this lab: 30 minutes

island from one format to

another by using the XML

Document Object Model

(DOM)

Explain the lab objectives

Trang 38

Exercise 1:

Transforming the XML Book Data into an <orderitem> Element

In this exercise, you will create a Click event procedure for the Add to Basket

button in Details.asp The event procedure will access the XML data island in Details.asp, which has the following format:

! Examine the contents of the XML book data island

1 Open Details.asp and locate the addToBasket_OnClick event procedure

The event procedure already contains script that accesses the dsoDetails data island, and retrieves the <title> and <isbn> values of the first book

2 Use a MsgBox function to display the existing contents of the XML data

island, which can be obtained by using docBook.xml

MsgBox docBook.xml

3 Save your changes to Details.asp

4 Test your changes:

a Go to the home page of the LitWare Books Web site and search for books written by Lars Peterson

b Select one of the books such as Straight Talk About Computers, and then

click Details

c Click Add to Basket to order a copy of this book

Trang 39

A message box should be displayed like the following illustration

! Create an XMLDOM object and load in an XSL style sheet

1 Copy the file TransformBookDetails.xsl from the folder <install

folder>\Labs\Labs06.1\Starter to the folder \InetPub\WWWRoot\LitWare

2 Open TransformBookDetails.xsl and familiarize yourself with its contents

The style sheet transforms a <book> element into an <orderitem> element

3 Open Details.asp and locate the comment Create an XML DOM object, and load an XSL stylesheet into it in the addToBasket_OnClick event

procedure

4 Create an XMLDOM object and save it in a variable named docStylesheet

5 Set the async property for the XMLDOM object to False

6 Use the load method of the XMLDOM object to load TransformBookDetails.xsl into the XMLDOM object

7 Use a MsgBox function to verify that the XSL style sheet was loaded

successfully The contents of the style sheet can be obtained by using docStylesheet.xml

To view an example of what the script should look like, see Appendix A or the Student CD-ROM

8 Save your changes to Details.asp

9 Test your changes:

a Go to the home page of the LitWare Books Web site and search for books written by Lars Peterson

b Select one of the books such as Straight Talk About Computers, and then

click Details

c Click Add to Basket to order a copy of this book

Trang 40

A second message box should be displayed like the following illustration

! Transform the <book> element into an <orderitem> element

1 In the addToBasket_OnClick event procedure in Details.asp, locate the comment Transform the new book node using the stylesheet

2 Create a second XMLDOM object to hold the transformed XML document Save the XMLDOM object in a variable named docTransformed

3 Transform the docBook XML data into the new format by using the

transformNodeToObject method of docBook as follows:

docBook.transformNodeToObject docStylesheet, docTransformed

4 Use a MsgBox function to verify that the transformation was successful

The contents of the transformed document can be obtained by using docTransformed.xml

To view an example of what the script should look like, see Appendix A or the Student CD-ROM

5 Save your changes to Details.asp

6 Test your changes by ordering another copy of the book Straight Talk About

Computers by Lars Peterson

Ngày đăng: 10/12/2013, 16:16