Tải bản đầy đủ (.pdf) (94 trang)

Module 6: Manipulating Cached XML

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.11 MB, 94 trang )








Contents
Overview 1
Lesson: Introduction to the XML
Document Object Model 2
Lesson: Navigating XML Using the DOM 14
Lab 6.1: Manipulating Cached
XmlDocument Objects (Optional) 37
Lesson: Creating New Nodes 43
Lesson: Modifying and Deleting Nodes 58
Review 72
Lab 6.1: Manipulating Cached
XmlDocument Objects 74
Course Evaluation 88

Module 6: Manipulating
Cached XML




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, place or event 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.

©2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Win32, Active Directory, ActiveX, BizTalk,
IntelliSense, JScript, Microsoft Press, MSDN, PowerPoint, SQL Server, Visual Basic, Visual C#,
and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 6: Manipulating Cached XML iii

Instructor Notes
After completing this module, students will be able to:

Open and save Extensible Markup Language (XML) documents by using
the Document Object Model (DOM).


Locate XML by using the DOM.

Create nodes in the XML node tree.

Modify and delete nodes in the XML node tree.

To teach this module, you need the following materials:

Microsoft
®
PowerPoint
®
file 2663A_06.ppt

Code Samples file 2663A_06_Code.htm

To prepare to effectively teach this module:

Read the entire module.

Complete the practices and the lab.

Practice delivering the demonstrations.

In this module, some of the PowerPoint slides provide hyperlinks that open a
code samples page in the Web browser. The code samples page provides a way
to show and discuss code samples when there is not enough space for the code
on the PowerPoint slide. It also allows students to copy code samples directly
from the browser window and paste them into a development environment. All

of the linked code samples for this module are in a single .htm file.
To open a code sample, click the appropriate hyperlink on the slide. To navigate
between code samples in a particular language, use the table of contents
provided at the top of the code page. Each hyperlink opens a separate instance
the Web browser, so it is a good practice to click Back in Microsoft
Internet Explorer after viewing a code sample. This will close the browser
window and return you to the PowerPoint presentation.
Presentation:
90 minutes

Lab:
105 minutes
Required materials
Preparation tasks
Hyperlinked Code
Examples
iv Module 6: Manipulating Cached XML


How to Teach This Module
This section contains information that will help you to teach this module.
Lesson: Introduction to the XML Document Object Model
This section describes the instructional methods for teaching each topic in this
lesson.
Explain what the Document Object Model (DOM) is, and the typical parts of an
XML document. Ask students if they have had any experience working with the
DOM and, if so, to describe what they have done.
Walk through the information on the slide and relate the XML document in the
text to the nodes on the slide graphic. Relate the elements and attributes of the
text to the nodes on the graphic.

This topic consists of a large table, most of which is on the slide. As you go
through the rows in the table, describe the purpose of each of the node types.
Point out the classes that descend from XmlNode and explain that the
descended classes represent what you find in an XML document. Take time to
establish the relationships of the derived classes.
This topic contains code samples that show how to load an XmlDocument
object from a file, stream, reader, or from a string.
This topic shows how use the Save() method of an XmlDocument object to
save the contents of the object to a file.
Lesson: Navigating XML Using the DOM
This section describes the instructional methods for teaching each topic in this
lesson.
This demonstration shows how to navigate nodes in an XML document. Be
sure to follow the navigation instructions exactly when you perform this
demonstration.
Explain how you can use an XmlNode object to refer to any of the descended
objects in a DOM tree.
Explain that when you have a node context, you can navigate around the
document by using relative navigational properties such as FirstChild,
NextSibling, and PreviousSibling.
Explain how to use the SelectSingleNode() property of an XmlDocument
object to provide random access to a single node in the tree. Contrast this
random approach to the relative approach you covered in the previous topic.
Explain how to use the XmlElement class to parse through an XmlDocument
object in memory and to examine its element nodes. You use the
GetAttribute() method of an XmlElement object to return the value of a
specific parameter.
What Is the XML
Document Object
Model?

How Dom Nodes
Correspond to XML
DOM Nodes and Related
.NET Node Types
What .NET Classes
Support the DOM?
How to Load a DOM
from an XML Source
How to Save a DOM to a
Document
Demonstration:
Navigating a Simple
Document
What Is the XmlNode
Class?
Using XmlNode
Properties
Referencing Individual
Nodes in an
XmlDocument Object
How to Parse an
XmlDocument Object in
Memor
y
Module 6: Manipulating Cached XML v

This topic describes how to populate an XmlNodeList object by using different
data sources.
Explain how to use a NamedNodeMap object to work with an unordered set of
nodes.


Follow the instructions carefully. Be sure to go through this code examination
in detail before teaching this lesson. As you go through the code, relate each
step to the previous topics in this lesson.
Lesson: Creating New Nodes
This section describes the instructional methods for teaching each topic in this
lesson.
Go through this demonstration carefully before teaching this lesson. This
demonstration sets up the remaining topics in this lesson by showing how to
add new nodes to an XmlDocument object in memory.
Explain the general algorithm for adding new nodes. Explain the three methods
that you use to add new nodes.
This topic uses detailed code examples to show how to create specific types of
nodes in an XML document that you have loaded into memory.
You can set and create attributes in one or two steps. Contrast the two
techniques for doing this.
This topic describes how to create nodes that contain comments, CDATA
information, and processing instructions.
This section examines in detail the content of the demonstration that began this
lesson. Be sure you are familiar with the code and what it does.

Lesson: Modifying and Deleting Nodes
This section describes the instructional methods for teaching each topic in this
lesson.
Contrast using the SelectSingleNode() method of an XmlNode object with
using the GetElementsByTagName to identify individual nodes.
Stress using the InnerText property to modify the contents of a node. Explain
that you cannot use the Value property for this purpose because it is a read-only
property.
This topic consists essentially of detailed code examples that show how to use

the RemoveChild() method of an XmlNode object to delete an element, and
how to use the RemoveAttribute() method of an XmlElement object to delete
an attribute.
This practice reinforces the content of the topics that describe how to modify
nodes.
What Is the XmlNodeList
Class?
What Is the
XmlNamedNodeMap
Class?
Code Examination:
Navigating a Simple
Document
Demonstration: Adding
Nodes to an
XmlDocument Object
How to add a Node to an
XmlDocument Object
How to Create an
Element Node
How to Set Attributes for
an Element Node
How to Create Other
Types of Nodes
Code Examination:
Adding Nodes to an
XmlDocument Ob
ject
How to Navigate to an
Existing Node

How to Modify a Node in
an XmlDocument Object
How to Delete a Node
from an XmlDocument
Object
Practice: Modifying
Nodes

Module 6: Manipulating Cached XML 1

Overview

Introduction to the XML Document Object Model

Navigating XML Using the DOM

Creating New Nodes

Modifying and Deleting Nodes

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
This module introduces the XML Document Object Model (XML DOM) and
explains how to locate and manipulate XML by using the DOM.
After completing this module, you will be able to:

Open and save XML by using the DOM.


Locate XML by using the DOM.

Create nodes in the XML node tree.

Modify and delete nodes in the XML node tree.

Introduction
Objectives
2 Module 6: Manipulating Cached XML


Lesson: Introduction to the XML Document Object Model

What Is the XML Document Object Model?

How DOM Nodes Correspond to XML

DOM Nodes and Related .NET Node Types

What .NET Classes Support the DOM?

How to Load a DOM from an XML Source

How to Save a DOM to a Document

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

******************************
This lesson gives an overview of the Document Object Model (DOM). You will
use this information to manipulate XML in other lessons in this course.
After completing this lesson, you will be able to:

Explain what the DOM is.

Build a DOM tree from an XML document.

Identify the .NET classes that support the DOM.

Load a DOM from an XML source.

Save a DOM to an XML document.

Introduction
Lesson objectives
Module 6: Manipulating Cached XML 3

What Is the XML Document Object Model?

DOM is the W3C programming interface for XML

DOM models an XML source
as a tree of nodes in memory

You can use DOM to:

Navigate and search


Add and delete content
City.xml
City.xml
City.xml in memory
City.xml in memory
<city>
<name
elev="9M">Svolvaer</name>
</city>
<city>
<name
elev="9M">Svolvaer</name>
</city>
DocumentNode
AttrNode
Element Node
Document Root
<city>
Element Node
<name>
elev=“9M”
TextCharacterData
Svolvaer
XML Example

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

The XML DOM provides a programming interface for applications to
manipulate XML. The World Wide Web Consortium (W3C) specification for
the DOM defines its properties, methods, and events.
You can use the DOM with Microsoft
®
XML Core Services 4 (MSXML4) or
Microsoft Visual Studio
®
.NET and the Microsoft .NET Framework classes to
search and edit XML data.
Both of these implementations fully support the W3C standard and provide
additional features that make it easier for you to program applications to work
with XML files.
The main reason to use the DOM is to cache XML data in memory, as opposed
to using an XmlReader or XmlWriter, which can only parse and generate
non cached documents. You should use the DOM whenever you need to
perform random-access style manipulation of XML data.
After an XML document is loaded into memory, an application can use the
DOM to:

Search for specific content.

Add, remove, or replace content.

Save the result to an XML file.

Introduction
Why use the DOM?
4 Module 6: Manipulating Cached XML



An application can use the DOM methods to create a representation in memory
of an XML source document. The DOM represents XML in memory as a tree
of node types. For example, the DOM maps the document element to a node
called DocumentNode and sets this value to the name of the document element.
You should use the DOM whenever you need to perform in-memory,
random access style modification of XML data.
Consider the following XML document, which represents a purchase order. It
might have several <date> elements, each appearing in a different part of the
document:
<order>
<date>02.01.03</date>
<item>canvas</item>
<reorder>
<date>02.07.04</date>
<item>linen</item>
</reorder>
</order>

An application that uses the DOM can recognize specific node types, such as
the document element and content, and then respond appropriately. For
example, the application can locate and update the occurrence of the <date>
element nested within the <reorder> element.
The DOM is not well suited to processing large XML files. Converting a large
XML data source into memory can cause some systems to slow down
dramatically. You might not need to load an XML document into memory to
process it. Consider the following scenarios.
To read and parse data from an XML document, you should use a strategy that
employs forward-only reading and parsing, without loading the document into
memory. In the .NET Framework, you can use an XmlTextReader or

XmlValidatingReader.
To query specific information from an XML document, you should use a
strategy optimized for querying non-cached data. In the .NET Framework, you
can use an XPathDocument object.
The DOM is not well suited to changing XML structure. If you want to convert
an XML document into another vocabulary, you use the Extensible Stylesheet
Language for Transformation (XSLT) instead of the DOM. In the
.NET Framework, you can use an XslTransform object.
When to use the DOM
Limitations of the DOM
Readin
g XML
Querying XML
Transforming XML
Module 6: Manipulating Cached XML 5

How DOM Nodes Correspond to XML
root
root
books
books
book
book
pubinfo
pubinfo
author
author
price
price
pubdate

pubdate
publisher
publisher
state
state
format
format
MSPress WA05/01/2001
31.95
Carson
DocumentType node
Document node
Element nodes
!DOCTYPE
Attribute node
Text nodes
Element nodes
Euro
XML Example

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The DOM class provides an in-memory representation of an XML document.
You use the DOM to programmatically read, manipulate, and modify an XML
document.
Before you can edit XML information by using the DOM, you must first load
the XML into memory. The XML document is represented in memory as a tree

that consists of various types of nodes.
The following XML represents a file with book publication information for a
book published by Microsoft Press
®
:
<?xml version="1.0"?>
<books>
<book>
<author>Carson</author>
<price format="Euro">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
</books>

Introduction
Example of building a
tree of nodes
6 Module 6: Manipulating Cached XML


As XML is read into memory as a DOM object, the DOM parser creates a tree
of nodes that represents the XML structure and content. The DOM parser
creates nodes, with each node type representing the various parts of an XML
document. Consider the following facts about DOM nodes:

Nodes have a single parent. The only node that does not have a parent is the

document root, because it is the top-level node and contains the document
itself in addition to document fragments.

Most nodes can have multiple child nodes. Nodes that can have child nodes
include Document, Document Fragment, Entity Reference, Element, and
Entity nodes.

Some nodes cannot have child nodes. These include XmlDeclaration,
Notation, CDATASection, Text, Comment, ProcessingInstruction, and
DocumentType nodes.

Attributes are not represented as nodes. In the DOM, attributes are
represented as properties of an Element node, and consist of a name and a
value. In the preceding example, the format attribute is a property of the
price element node and has a value of “Euro”.

How XML is represented
in a DOM object
Module 6: Manipulating Cached XML 7

DOM Nodes and Related .NET Node Types
XmlNotationNotation
XmlEntityEntity
XmlCDATASectionCDATASection
XmlTextText
XmlCommentComment
XmlProcessingInstructionProcessingInstruction
XmlAttributeAttr
XmlElementElement
XmlEntityReferenceEntityReference

XmlDocumentTypeDocumentType
XmlDocumentFragmentDocumentFragment
XmlDocumentDocument
Related .NET DOM node type
Related .NET DOM node type
W3C DOM node types
W3C DOM node types

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When an XML document is read into memory as a tree of nodes, the DOM
determines the node type for each component of the XML document. The DOM
has several different kinds of node types. These types are specified by the W3C.
Determining a node’s type is important when parsing through a tree of nodes.
You can write code to perform different actions such as modifying or retrieving
information based on the type of node that you are examining.
The .NET Framework contains several classes that map to the W3C node types
in the DOM, as described in the following table.
W3C DOM node type .NET class Description

Document XmlDocument The container for all nodes
in the tree
DocumentFragment XmlDocumentFragment A container for nodes
without a tree structure
DocumentType XmlDocumentType <!DOCTYPE...> node
EntityReference XmlEntityReference An entity reference
Element XmlElement An element node

Attr XmlAttribute An attribute of an element
ProcessingInstruction XmlProcessingInstruction A processing instruction
Comment XmlComment A comment
Text XmlText Text that belongs to an
element or attribute
CDATASection XmlCDATASection A CDATASection
Entity XmlEntity An XML entity
Notation XmlNotation Notation in a DTD

Introduction
How W3C node types
map to .NET
8 Module 6: Manipulating Cached XML


The .NET Framework also contains five additional node types that are not
defined by the W3C, as described in the following table.
Node type Description

XmlDeclaration The XML declaration; for example,
<?xml
version="1.0"?>

XmlSignificantWhitespace An XML significant white space
XmlWhiteSpace An XML white space
EndElement Returned by an XmlReader when reaching an end
element; for example, </item>
EndEntry An end entry

Additional .NET node

types
Module 6: Manipulating Cached XML 9

What .NET Classes Support the DOM?
.NET Framework DOM class hierarchy
Object
XmlNode
XmlLinkedNode
XmlCharacterData
XmlDeclaration
XmlDocumentType
XmlElement
XmlEntityRef
XmlProcessingInstruction
XmlAttribute
XmlDocument
XmlDocumentFragment
XmlDocumentType
XmlEntity
XmlNotation
XmlNamedNodeMap
XmlAttributeCollection
XmlNodeList
XmlCDATASection
XmlComment
XmlSignificantWhiteSpace
XmlWhiteSpace

*****************************
ILLEGAL FOR NON

-
TRAINER USE
******************************
The .NET Framework contains objects that implement the W3C
recommendations for the DOM. The .NET Framework supports the DOM
Level 1 and Core DOM Level 2.
Many of the classes that you will use to manipulate and parse XML documents
inherit from the XmlNode object.
The XmlDocument object acts as a container for an XML document. You
typically create an XmlDocument object and load it with XML from a file,
string, or stream. You will see how to create and populate an XmlDocument
object in the topic How to Load a DOM from an XML Source in this lesson.
After the XML source is loaded into an XmlDocument object, you can parse
and modify the individual nodes in the tree. You typically load a variable of
type XmlNode and examine its properties to determine the specific node type
and value.
The W3C DOM also describes a NodeList, which is used to contain an ordered
list of nodes. The XmlNodeList class implements the NodeList in the
.NET Framework.
You typically use an XmlNodeList to hold the nodes selected by a query
against an XML document. To process the results, you can iterate through this
collection of nodes with a loop or by using a For-Each style of iteration over the
collection of nodes.
In addition, the XmlNamedNodeMap is designed to contain an unordered set
of nodes. To process the nodes, you can refer to individual nodes by their name
or index.
You will use these objects in a later lesson to parse and modify an in-memory
XML document.
Introduction
Using the objects that

inherit from XmlNode
Using XmlNodeList and
XmlNamedNodeMap
10 Module 6: Manipulating Cached XML


How to Load a DOM from an XML Source
C# ExampleVisual Basic Example

Load DOM by using the XmlDocument object

The method to use depends on the type of object you
are loading
Load()Stream
File
XmlReader
TextReader
LoadXml()String
Use this method:
Use this method:
To load XML from this type:
To load XML from this type:

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You create an XmlDocument object to contain and manipulate XML data by
using the DOM. First, you must instantiate an XmlDocument object. Then you

can load data by using either the Load() or Load Xml() method.
You can create a new XmlDocument object by calling the class constructor
with no parameters as in the following examples. Examples are given in both
Microsoft Visual Basic
®
and Microsoft Visual C#

.
'Visual Basic
Imports System.Xml
Dim doc As New XmlDocument()

// C#
Using System.Xml;
XmlDocument doc = new XmlDocument();

Introduction
Instantiating an
XmlDocument object
Module 6: Manipulating Cached XML 11

You can load an XmlDocument with data from a file, stream, XmlReader, or
TextReader by using the Load() method of the XmlDocument object.
The following example creates a new XmlDocument object and populates it
with data from a file:
// C#
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("C:\\BookData.xml");


'Visual Basic
'Create the XmlDocument.
Dim doc As XmlDocument = New XmlDocument()
doc.Load("C:\\BookData.xml")

You can load an XmlDocument object with data from a string by using the
LoadXml() method of the XmlDocument object.
The following example creates a new XmlDocument object and populates it
with data from a string:
// C#
public class LoadXmlString
{
public static void Main()
{
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>"
+ "<title>Pride And Prejudice</title>" +
"</book>");
}
}

'Visual Basic
Public Class LoadXmlString

Public Shared Sub Main()
'Create the XmlDocument.
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" _
+ "<title>Pride And Prejudice</title>" + "</book>")

End Sub

End Class

Loading an
XmlDocument from a
file, stream, or reade
r
Loading an
XmlDocument from a
string
12 Module 6: Manipulating Cached XML


How to Save a DOM to a Document

Use the Save() method to save XML from an
XmlDocument object to a:

file

Stream

TextWriter

XmlWriter

Save() method syntax
C# Example
XmlDocument.Save(filename | Stream | TextWriter | XmlWriter)

XmlDocument.Save(filename | Stream | TextWriter | XmlWriter)
Visual Basic Example

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can save the contents of an XmlDocument object to a file by using the
Save() method.
The Save() method of the XmlDocument object is overloaded to accept a file,
stream, XmlWriter, or TextWriter as a parameter.
The following code is the syntax for using the Save() method:
XmlDocument.Save(filename | stream | TextWriter | XmlWriter)

Introduction
Savin
g XML to a file
Module 6: Manipulating Cached XML 13

The following code fragment loads a price list into an XmlDocument object. It
then calls a custom method named IncreasePrice that modifies the XML in
memory. (Note that this example does not include code for this method.)
Finally, the code saves the data to a new XML file.
// C#
try
{
// Create XmlDocument, load from file
XmlDocument MyXmlDocument = new XmlDocument();
MyXmlDocument.Load (new XmlTextReader(DataDocument));


// Modify the XML in memory
IncreasePrice(MyXmlDocument.DocumentElement);

// Write out data as XML
MyXmlDocument.Save(UpdatedDocument);

}

catch (Exception e)
{
MessageBox.Show(e.ToString());
}

'Visual Basic
Try
'Create XmlDocument, load from file
Dim MyXmlDocument As XmlDocument = New XmlDocument()
MyXmlDocument.Load(New XmlTextReader(DataDocument))

'Modify the XML in memory
IncreasePrice(MyXmlDocument.DocumentElement);

'Write out data as XML
MyXmlDocument.Save(UpdatedDocument)

Catch e As Exception
MessageBox.Show(e.ToString())
End Try


Example
14 Module 6: Manipulating Cached XML


Lesson: Navigating XML Using the DOM

Demonstration: Navigating a Simple Document

What Is the XmlNode Class?

Using XmlNode Properties

Referencing Individual Nodes in an XmlDocument
Object

How to Parse an XmlDocument Object in Memory

What Is the XmlNodeList Class?

What Is the XmlNamedNodeMap Class?

Code Examination: Navigating a Simple Document

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this lesson, you will learn how to navigate XML and locate nodes by using
the DOM.

After completing this lesson, you will be able to:

Describe the XmlNode class.

Use XmlNode properties.

Reference individual nodes in an XmlDocument object.

Parse an XmlDocument object in memory by using XML elements.

Describe the XmlNodeList class.

Describe the XmlNamedNodeMap class.

Load XML by using the DOM.

Introduction
Lesson ob
jectives
Module 6: Manipulating Cached XML 15

Demonstration: Navigating a Simple Document

A Windows Application navigates through
an XML document

Notice how it loads XML data into memory
by using an XmlDocument object

Notice how it uses the following methods

to navigate nodes:

XmlDocument

XmlElement

XmlNode

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In this demonstration, you will see how to navigate through an XML document
by using a Microsoft Windows
®
Application. This application loads XML data
into memory by using an XmlDocument object. It then uses methods and
properties of the XmlDocument, XmlNode, and XmlElement objects to
navigate nodes.
Instructor
Do not show the underlying code. The purpose of this demonstration is to
show the action of identifying and navigating through nodes in a document.
You will show the code at the end of the lesson.


To set up the demonstration
1. In Visual Studio .NET, open the project NavigateXmlDoc.
2. Build and run the application.
3. Click Load Document, and then examine the entire XML document.



To navigate nodes
1. Click Get Document Element and examine the results.
2. Click Get First Child. Notice that this returns a node containing the first
book information.
3. Click Get Last Child. This returns a node containing the price element of
the first book.
4. Click Get Last Child again. This returns the text node of the price element.
5. Click Get Last Child again. This generates an error because the current
node is a leaf node and there are no remaining children.
Introduction
Note
Demonstration
16 Module 6: Manipulating Cached XML


6. Click Get Parent Node twice to make the current node point to the first
book.
7. Click Get Next Sibling to return a node containing the second book.
8. Click Get Previous Sibling to point to the first book.


To return nodes by element name
1. In the Locate an element group, type last-name in the text box, and then
click Find.
2. Examine the output. Notice that this contains all of the last-name elements
in the document.



To locate a single element by value
1. In the Find element by value group, type Melville in the text box, and then
Click Find.
2. Examine the output. Notice that this contains the book element containing a
last-name element with a value of Melville.
3. Type Austen in the text box and then click Find.
4. Examine the output. Notice that this contains only the first book element
containing a last-name element with a value of Austen.

Module 6: Manipulating Cached XML 17

What Is the XmlNode Class?

Used to handle XML by its node characteristics

Acts as a pointer to nodes when navigating a document

Base class for

XmlDocument

XmlDocumentFragment

XmlEntity

XmlLinkedNode

XmlAttribute

XmlNotation

C# ExampleVisual Basic Example

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
In the .NET Framework, an XmlNode instance represents a single node in an
XML document.
Many classes that represent nodes in the DOM inherit from the XmlNode class.
The XmlDocument, XmlDocumentFragment, XmlAttribute, XmlEntity,
and XmlNotation classes all inherit functionality from the XmlNode class.
Many classes that define nodes in an XmlDocument object inherit from an
abstract class called XmlLinkedNode, which in turn inherits from XmlNode.
These classes include XmlElement, XmlProcessingInstruction,
XmlCharacterData, and XmlDeclaration. All of these classes represent types
of nodes in an XmlDocument object.
After creating an XmlDocument object and loading it with XML data, you
generally should parse and navigate through the data or add, delete, or modify
nodes.
You typically create and use new XmlNode objects to help you navigate in an
XmlDocument object, or to create or modify nodes in the XmlDocument
object. The XmlNode object can act like a pointer or cursor to nodes in the
structure of an XmlDocument object. Because many nodes in an
XmlDocument object inherit from the XmlNode class, you can use an
XmlNode object to refer to any of these nodes in the XmlDocument object.
After you have selected a node in the XmlDocument object, you can extract
information by examining properties, and modify the content, insert new nodes,
or delete existing nodes.
Introduction

Inheriting from the
XmlNode class
Why use the
XmlNode
class?
18 Module 6: Manipulating Cached XML


The following code fragment creates a new XmlDocument object and loads it
from a file. It then creates a new XmlNode object to identify the Document
element of the XmlDocument object. After you set the current node, the code
extracts property information from the node, and creates another node that acts
similarly to a cursor in order to iterate through all of the nodes and print out
their contents.
// C#
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");

//Display all the books

XmlNode root = doc.DocumentElement;
IEnumerator NodePointer = root.GetEnumerator();

XmlNode book;
while (NodePointer.MoveNext())
{
book = (XmlNode) NodePointer.Current;
MessageBox.Show(book.OuterXml);

}


'Visual Basic
Dim doc As XmlDocument = New XmlDocument()
doc.Load("books.xml")

'Display all the books
Dim root As XmlNode = doc.DocumentElement
Dim NodePointer As IEnumerator = root.GetEnumerator()

Dim book As XmlNode
While NodePointer.MoveNext()
book = CType(NodePointer.Current, XmlNode)
MessageBox.Show(book.OuterXml)
End While

Example
Module 6: Manipulating Cached XML 19

Using XmlNode Properties

XmlElement and XmlAttribute objects are also nodes

To access content, use properties and methods
C# Example
XmlNode book = doc.FirstChild;
XmlNode priceNode = book.ChildNodes[1];
XmlNode isbnNode = book.GetAttributeNode("isbn");
string price = priceNode.FirstChild.Value;
string isbn = isbnNode.Value;
XmlNode book = doc.FirstChild;

XmlNode priceNode = book.ChildNodes[1];
XmlNode isbnNode = book.GetAttributeNode("isbn");
string price = priceNode.FirstChild.Value;
string isbn = isbnNode.Value;
<?xml version="1.0"?>
<book isbn="123456789">
<title>XML.NET</title>
<price>19.99</price>
</book>
<?xml version="1.0"?>
<book isbn="123456789">
<title>XML.NET</title>
<price>19.99</price>
</book>
Visual Basic Example

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can use the properties of the XmlNode object and its descendants to return
information about the contents of an XML source document, and to help you
navigate within the XmlDocument object in memory.
When parsing an XML document, you often use two different types of
properties together. These properties can be divided into two basic categories,
informational and navigational, as outlined in the following tables, which show
some of the available properties.
Property Description


InnerText The concatenated values of the node and all of its children. The returned
string does not contain the XML markup.
InnerXml A string containing the markup of the children of this node.
Name The qualified name of the node.
Node type The type of the node (Document, Element, Attribute, Comment, and
so on).
Value The content of the node, returned as a string as applicable.

Introduction
Using
XmlNode
properties
Informational properties

×