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

Tài liệu Module 5: Creating and Manipulating Trees Using DOM ppt

32 530 0
Tài liệu đã được kiểm tra trùng lặp

Đ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 đề Creating and manipulating trees using dom
Trường học Microsoft Corporation
Thể loại module
Năm xuất bản 2001
Thành phố Redmond
Định dạng
Số trang 32
Dung lượng 857,77 KB

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

Nội dung

"Search the DOM memory structure" Doc element Element Element Attribute Attribute Text Document Element XML Source MyXmlDoc.Load"Source.xml" MyXmlDoc.Save"Result.xml" "Save the result" D

Trang 1

Contents

Overview 1

Lesson: How Does DOM Work? 2

Lesson: Using DOM and the NET

Trang 2

Information in this document, including URL and other Internet Web site references, is subject to change without notice Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, places or events is intended or should be inferred Complying with all applicable copyright laws is the responsibility of the user Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation 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

 2001 Microsoft Corporation All rights reserved

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BackOffice, bCentral, BizTalk, FrontPage, MSDN, MSN, Netshow, PowerPoint, SharePoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual Studio, Windows Media, and Xbox are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries The names of actual companies and products mentioned herein may be the trademarks of their respective owners

Trang 3

Succinctly explain the concepts and the role of DOM in the work of the World

Wide Web Consortium (W3C) Be sure to make it clear why DOM is needed

After completing this module, participants will be able to:

! Describe the basic nature of the Document Object Model (DOM)

! Load an XML document into memory

! Navigate a tree to find data

! Retrieve and set node properties

! Save a DOM tree to an XML file

Materials and Preparation

This section provides the materials and preparation tasks that you need to teach this module

To teach this module, you need the following materials:

! Microsoft PowerPoint® file 2500A_05.ppt

! XML Tree Viewer

To prepare for this module:

! Read all of the materials for this module and complete the labs

! Read about DOM in the NET Framework software development kit (SDK)

! Read the W3C materials about DOM so that you can comfortably show them to the class and comment on them briefly

! Develop as thorough an understanding as you can about the way DOM interacts with other XML technologies, because some participants may have questions about this

Although Course 1905B, Building XML-Based Web Applications,

contains a chapter on DOM, you can only refer to it for comparison purposes, because it is based on Microsoft Visual Basic® version 6.0 techniques and code

Trang 4

Module Strategy

This module describes how to use Microsoft Visual Studio® NET and the NET XML classes to implement basic DOM functionality

Use the following strategy to present this module:

! How Does DOM Work?

This lesson introduces how DOM applications work Explain how the NET Framework XML classes enable developers to use and extend the W3C XML DOM by using base and extended classes Direct participants to the shortcut that Visual Studio NET installs on the Desktop that opens the Microsoft NET Framework SDK Emphasize the importance of using the SDK when developing with the NET Framework XML classes

! Using DOM and the NET Framework XML Classes This lesson builds a basic DOM solution by using the NET Framework XML classes This lesson first describes how to load an XML document or string Then, it describes how to search and manipulate the data Finally, it describes how to save the result as a new XML file

Trang 5

Overview

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

The Document Object Model (DOM) is an important technology to know when working with XML documents This module introduces DOM and how it is enabled in the Microsoft® NET Framework environment

For more information on DOM, see the DOM page on the W3C site at http://www.w3.org/dom

After completing this module, you will be able to:

! Describe the basic nature of the Document Object Model (DOM)

! Load an XML document into memory

! Navigate a tree to find data

! Retrieve and set node properties

! Save a DOM tree to an XML file

Introduction

Note

Objectives

Trang 6

Lesson: How Does DOM Work?

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

After completing this lesson, you will be able to:

! Describe how a DOM application works

! Describe how the NET Framework XML Classes enable you to create a DOM application

Lesson objectives

Trang 7

How Does a DOM Application Work?

"Search the DOM memory structure"

Doc element

Element Element

Attribute Attribute Text

Document

Element

XML Source

MyXmlDoc.Load("Source.xml")

MyXmlDoc.Save("Result.xml")

"Save the result"

Dim List As XmlNodeList MyXmlDoc.LoadXml(MyXmlData) List = myXmlDoc.GetElementsByTagName("Test") DOM memory structure

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

To use DOM, you need an XML processor that implements DOM The Microsoft XML Parser (MSXML) version 2.0 implements DOM

The following procedure describes the steps a typical DOM application uses to process XML:

1 The application instructs the XML processor to load an XML document into memory by using its DOM filter

2 The XML processor DOM filter loads the XML document into memory as a tree of nodes

3 The application performs some operation on the DOM tree in memory The application can locate a node according to some criterion that you specify, such as by node type or node content When the application locates a node

or set of nodes, it can perform some processing, such as change the node content or add nodes

4 The application can save the result as a new XML file or transmit the XML result to some other software module for further processing

Introduction

How a typical DOM

application processes

XML

Trang 8

An XML document is only one of many possible sources of XML An XML source can be a section of XML data that is contained within a:

! String variable

! Text document

! Hypertext Markup Language (HTML) file

! Microsoft SQL Server™ 2000 database table

DOM provides a set of techniques for modifying the document tree You can convert an original document that has been loaded into memory into some other tree structure that suits a different purpose

For example, one part of your order tracking system uses package tracking data that is generated by one of four possible delivery vendors The structure of the package tracking data depends on which vendor was used to send the package You can write an application that processes incoming package tracking data depending on the vendor who sends it Then, you can apply a different DOM conversion routine so that the package tracking data conforms to your system requirements regardless of its origins

What is an XML source?

DOM Use Case

Trang 9

What Are the NET Framework XML Classes?

! Classes that reflect and extend DOM

! Base classes

" XmlNode represents a single node

" XmlNodeList represents a node list

" XmlNamedNodeMap represents named nodes

! Extended classes

" Inherit from XmlNode

" Used to create objects corresponding to DOM node objectsXmlElement represents an element

XmlAttribute represents an attributeXmlComment represents a commentMany others

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

The World Wide Web Consortium (W3C) developed DOM in levels DOM Level 1 and Level 2 have reached Recommendation status A third level is in the Working Draft stage of development

The Microsoft NET Framework software development kit (SDK) fully supports and extends the classes described in the W3C DOM Level 1 and Level 2 Recommendations These extensions to DOM make it easier to work with XML data For example, several of the new classes enable you to access relational data They give you methods for synchronizing with ADO.NET data and simultaneously exposing data as XML

If you want to use Microsoft Visual Studio® NET to write a program that uses DOM, you will most likely use the following XML DOM base classes

Use the members of this class: To represent:

XmlNode A single node in the document tree It is the base

class for accessing data in the XML object model

The XmlNodeType enumeration defines valid

node types

XmlNodeList An ordered collection of nodes It supports

iteration and indexed access methods on the live

collection of XmlNode objects This object

immediately mirrors changes to the document

XmlNamedNodeMap A collection of nodes that can be accessed by name

or index It provides iteration and access by name

to the collection of attributes This class includes support for namespaces

Introduction

XML DOM base classes

Trang 10

The extended classes enable you to create objects that correspond to the DOM node types found in XML documents Most of these objects inherit properties

and methods of the base XmlNode object

Class Description XmlDocument Represents the top node of the XML document The

XmlDocument class implements the W3C DOM Core

Level 1 and the DOM Core Level 2

XmlAttribute Represents an attribute of the XmlElement object

Valid and default values for the attribute are defined in

a document type definition (DTD) or schema

XmlAttributeCollection Represents attributes of the XmlElement object Valid

and default values for the attribute are defined in a DTD or schema

XmlCDataSection Includes blocks of text containing characters that

would otherwise be recognized as markup These characters are included in their literal forms, without expanding entities or interpreting element tags

XmlCharacterData Provides methods for text manipulation that are used

by other classes, such as XmlText and

XmlCDataSection

XmlComment Represents the content of an XML comment

XmlDeclaration Represents the XML declaration nodes,

<?xml version='1.0' … ?>

XmlDocumentFragment Represents a fragment or portion of a document’s tree

This is useful for tree insert operations

XmlDocumentType Contains information associated with the document

type declaration

XmlElement Represents an element object

XmlEntity Represents a parsed or unparsed entity in the XML

document

XmlEntityReference Represents an entity reference node

XmlImplementation Provides methods for performing operations that are

independent of any particular instance of DOM

XmlLinkedNode Gets the node immediately preceding or following this

node Nodes as the instance of this class or classes derived from it can be linked inside the DOM tree and their proceeding or following nodes can be retrieved

XmlNotation Contains a <!NOTATION declared in the DTD or

schema

XML DOM extended

classes

Trang 11

(continued)

Class Description XmlNamedNodeMap Represents the collection of nodes that can be accessed

by name or index

XmlProcessingInstruction Represents a processing instruction that XML defines

to keep processor-specific information in the text of the document

XmlSignificantWhitespace Represents the significant white space in the content of

an element, attribute, or the text of the document

XmlWhitespace Represents white space in the content of an element

or attribute

XmlText Represents the text content of an element or attribute

Trang 12

Lesson: Using DOM and the NET Framework XML

Classes

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

In this lesson you will learn how to build an application that uses the NET Framework XML classes that use DOM functionality

After completing this lesson, you will be able to:

! Load an XML source into memory as a DOM node tree

! Navigate a DOM node tree

! Retrieve and manipulate the data and the properties of DOM nodes

! Save a DOM node tree as an XML file

If you have not yet looked at the NET Framework and NET languages,

do not be too concerned However, it is important to know that Microsoft Visual Basic® NET is very different from Visual Basic version 6.0 and is effectively a new language For more information about Visual Basic NET, see

Course 2559A, Introduction to Visual Basic NET Programming

Introduction

Lesson objectives

Note

Trang 13

How to Load an XML Source

Dim myxmlDoc as XmlDocument()myxmlDoc.Load("c:\mydata\pets.xml")

Dim myxmlDoc as XmlDocument()myxmlDoc.Load("c:\mydata\pets.xml")

Dim myXMLData As String = _

"<pets>" & _

" <pet>" & _ …Dim myxmlDoc as XmlDocument()myxmlDoc.LoadXML(myXMLData)

Dim myXMLData As String = _

"<pets>" & _

" <pet>" & _ …Dim myxmlDoc as XmlDocument()myxmlDoc.LoadXML(myXMLData)

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

The first step in using DOM is to load the XML source into a DOM node tree

First you must define an XML document object and then use the Load method

to fill the object with data from a file

The following code loads an external file:

Dim myxmlDoc As New XmlDocument() [other code might go here]

myxmlDoc.Load("c:\mydata\pets.xml") You can also load XML data from the program file itself To do this, you use a

string variable to contain the XML data to load Then, you use the LoadXML method instead of the Load method, as follows:

Dim myXMLData As String = _ "<pets>" & _ " <pet>" & _ " <breed>Moggie</breed>" & _ " <color>black</color>" & _ " <name>Alberta</name>" & _ " <weight>5</weight>" & _ " </pet>" & _

[etc]

"</pets>"

… Dim myxmlDoc As New XmlDocument()

myxmlDoc.LoadXml(myXMLData)

Introduction

How to load a document

into a DOM tree

How to load XML from a

string into a DOM tree

Trang 14

How to Navigate the DOM Node Tree

Dim demoPetNodes As XmlNodeListDim demoPetNode As XmlNodeDim domDataNodes As XmlNodeListDim domDataNode As XmlNode

…myxmlDoc.LoadXml(myXMLData)demoPetNodes =

myxmlDoc.GetElementsByTagName("pet")For Each demoPetNode In demoPetNodesdomDataNodes = demoPetNode.ChildNodes …

Dim demoPetNodes As XmlNodeListDim demoPetNode As XmlNodeDim domDataNodes As XmlNodeListDim domDataNode As XmlNode

…myxmlDoc.LoadXml(myXMLData)demoPetNodes =

myxmlDoc.GetElementsByTagName("pet")For Each demoPetNode In demoPetNodesdomDataNodes = demoPetNode.ChildNodes …

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

After the tree is loaded with XML data, you can locate particular nodes for further processing, manipulation, or modification

Having retrieved information from the pets XML data, the tree is then populated with information about all the pets listed You can retrieve information about the pets by accessing the nodes of the tree and returning information about them

The following is an example of how the data for the <pet> nodes and child

nodes can be retrieved Notice the use of the innerText property

Dim demoPetNodes As XmlNodeList Dim demoPetNode As XmlNode Dim domDataNodes As XmlNodeList Dim domDataNode As XmlNode

… myxmlDoc.LoadXml(myXMLData) demoPetNodes = myxmlDoc.GetElementsByTagName("pet") For Each demoPetNode In demoPetNodes

domDataNodes = demoPetNode.ChildNodes

…[other code goes here]

Console.Out.Write(domDataNode.Name & ": " &

domDataNode.InnerText) When the complete code runs, it produces the following output to a console window

Introduction

Example

Trang 15

How to Retrieve and Manipulate Properties and Data

Dim petAttributes As XmlAttributeCollectionDim petAttribute As XmlAttribute

Dim age As Decimal

…petAttributes = node.Attributes()For Each petAttribute In petAttributes

If petAttribute.Name = "age" Thenage = petAttribute.InnerXml

End If

If age >= 12 ThenpetAttributes.ItemOf("ageyears").Value = age / 12Else

petAttributes.ItemOf("agemonths").Value = ageEnd If

Dim petAttributes As XmlAttributeCollectionDim petAttribute As XmlAttribute

Dim age As Decimal

…petAttributes = node.Attributes()For Each petAttribute In petAttributes

If petAttribute.Name = "age" Thenage = petAttribute.InnerXml

End If

If age >= 12 ThenpetAttributes.ItemOf("ageyears").Value = age / 12Else

petAttributes.ItemOf("agemonths").Value = ageEnd If

Visual Basic Example Visual C# Example

***************************** ILLEGAL FOR NON - TRAINER USE ******************************

You can locate the contents of a node by retrieving the values contained within

an attribute or element

To read the contents of attributes, do the following:

1 Create a variable of the XmlAttributeCollection type and another of the XmlAttribute type

2 Load the XmlAttributeCollection variable with attribute data by using the node.Attributes method The XmlAttributeCollection variable now

contains a list of all the attribute values in the XML source

3 Assign content to the XmlAttribute variable in a conditional expression

that tests for the presence or absence of a particular attribute value

Introduction

How to read the

contents of attributes

Trang 16

In this example, the petAttributes collection is built with a search of the attributes items Within those items, the age attribute is retrieved and its value (petAttribute.InnerXml) is used to do the calculations in the second IF

statement The source document is loaded in the last code block

Dim petAttributes As XmlAttributeCollection Dim petAttribute As XmlAttribute

Dim age As Decimal

… petAttributes = node.Attributes() For Each petAttribute In petAttributes

If petAttribute.Name = "age") Then age = petAttribute.InnerXml

End If

If age >= 12 Then petAttributes.ItemOf("ageyears").Value = age / 12 Else

petAttributes.ItemOf("agemonths").Value = age End If

[other code here]

myxmlDoc.Load(" \pets3.xml") petNodes = myxmlDoc.GetElementsByTagName("pet") For Each petNode In petNodes

ModifyAttributes(petNode) Next

[other code here]

You can modify the DOM tree in many ways by adding or removing elements

or attributes, by modifying tree structures, and by creating entirely new documents from input XML documents or XML data from other sources (for example, inline in a file)

Example

How to add an attribute

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

TỪ KHÓA LIÊN QUAN