You are on page 1of 40

XML Programming

Using C# and .NET

E. J. Jones
Robert J. Oberg
William W. Provost

Student Guide
Revision 2.1

Object Innovations Course 414


XML Programming Using C# and .NET
Rev. 2.1

Student Guide

Information in this document is subject to change without notice. Companies, names and data
used in examples herein are fictitious unless otherwise noted. 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 Object Innovations.

Product and company names mentioned herein are the trademarks or registered trademarks of
their respective owners.

Copyright © 2006 Object Innovations. All rights reserved.

Object Innovations
877-558-7246
www.objectinnovations.com

Printed in the United States of America.

Rev. 2.1 Copyright © 2006 Object Innovations ii


All Rights Reserved
Table of Contents (Overview)

Chapter 1 .NET Framework XML Overview


Chapter 2 Reading XML Streams in .NET
Chapter 3 Validating XML Streams
Chapter 4 Writing XML Streams in .NET
Chapter 5 The Document Object Model in .NET
Chapter 6 Manipulating XML Information with the DOM
Chapter 7 Using XML Schema
Chapter 8 XML Serialization
Chapter 9 XML and ADO.NET
Chapter 10 XPath
Chapter 11 Introduction to XSLT
Chapter 12 XML Performance Tradeoffs

Appendix A Zenith Courseware Case Study


Appendix B Learning Resources

Rev. 2.1 Copyright © 2006 Object Innovations iii


All Rights Reserved
Prerequisites and Pacing

• C# programming experience is required for this


course.
• Some experience with XML is also assumed.
− The student should understand basic XML grammar, and be
able to read and write well-formed XML documents.
− The concept of a valid XML document, as opposed to a
merely well-formed one, should be understood, via some
experience with either DTDs or XML Schema.

• This course contains a great deal of material.


− Please give feedback to the instructor at the beginning of the
course on the topics of most interest to you, and during the
course about how the pacing is working for you.

Rev. 2.1 Copyright © 2006 Object Innovations iv


All Rights Reserved
Labs

• The course relies on hands-on experience in various


topics and techniques.
• Application code for this course is all in XmlCs under
the top-level directory, which by default is c:\OIC.
• Where possible, starter code is provided to take work
off your hands that would be largely irrelevant to the
topic of the lab; thus you can be as productive as
possible in the time allotted and focus on the topic at
hand.
• The labs are installed by running the simple self-
extractor:
Install_XmlCs_21.exe

− This can be found in the file 414_Lab_21.zip, which is


available on Object Innovations’ lab download page:
http://www.objectinnovations.com/Labs/index.html

Rev. 2.1 Copyright © 2006 Object Innovations v


All Rights Reserved
Directory Structure for the Course

• The course has a combination of directories under the


course root directory c:\OIC\XmlCs.
− Under this root, the chapter directories Chap01, Chap02,
and so on, hold code examples, including all the starting,
intermediate and answer versions of all the labs.
− The Labs directory holds one subdirectory for each lab in the
course, named for the lab number.
− The Demos directory is provided for performing in-class
demonstrations led by the instructor.
− The Tools directory contains the executables of XML tools
that are provided with the course, and also the source code
for the XPath/XSLT console program xtcon.exe.
− The CaseStudy directory contains files pertaining to the
Zenith Courseware case study.

• Data files install to the directory c:\OIC\Data.

Rev. 2.1 Copyright © 2006 Object Innovations vi


All Rights Reserved
Table of Contents (Detailed)

Chapter 1 .NET Framework XML Overview .............................................................. 1


XML................................................................................................................................ 3
Parsing XML................................................................................................................... 4
Using XML in .NET Applications.................................................................................. 5
The .NET XML Classes.................................................................................................. 7
Parsing Techniques ......................................................................................................... 9
.NET Parsing Techniques ............................................................................................. 10
Parsing Example ........................................................................................................... 11
How Does SAX and MSXML Fit Into .NET?.............................................................. 12
XmlReader and XmlWriter Features ............................................................................ 13
XmlTextWriter Demo................................................................................................... 15
.NET DOM Parser Features.......................................................................................... 17
XmlDocument Demo .................................................................................................... 18
Demo – Testing Parser Features ................................................................................... 19
Other XML Features in .NET ....................................................................................... 23
XML and the Web ........................................................................................................ 24
Internet Explorer and XML .......................................................................................... 25
Summary ....................................................................................................................... 26
Chapter 2 Reading XML Streams in .NET ................................................................ 27
The .NET XmlReader Classes ...................................................................................... 29
The XmlReader Properties............................................................................................ 30
Accessing Nodes........................................................................................................... 31
Reading Attributes ........................................................................................................ 32
MoveToNextAttribute................................................................................................... 33
XmlTextReader Example.............................................................................................. 34
Using Streams with XmlTextReader ............................................................................ 35
The XmlTextReader Demo........................................................................................... 36
Catching the Exceptions ............................................................................................... 40
Lab 2A .......................................................................................................................... 42
Moving Around the Document ..................................................................................... 43
MoveReader Example................................................................................................... 44
Handling Whitespace .................................................................................................... 45
Parsing a Specific Document ........................................................................................ 46
Parsing the Top-Level Elements................................................................................... 47
Subroutines ................................................................................................................... 48
Looping for Children .................................................................................................... 49
Text via Brute Force ..................................................................................................... 50
ReadElementString()..................................................................................................... 51
Zenith Courseware Case Study..................................................................................... 52
Lab 2B........................................................................................................................... 53
Miscellaneous Reading Methods .................................................................................. 54
Handling Namespaces................................................................................................... 55

Rev. 2.1 Copyright © 2006 Object Innovations vii


All Rights Reserved
The XmlNodeReader Class........................................................................................... 57
Creating XmlReaders in .NET 2.0................................................................................ 59
Benefits of Using XmlReader.Create()......................................................................... 60
Summary ....................................................................................................................... 61
Chapter 3 Validating XML Streams ........................................................................... 69
Valid XML.................................................................................................................... 71
The Trouble with Well-Formed XML .......................................................................... 72
Formal Type Information.............................................................................................. 73
DTDs and XML Schema .............................................................................................. 74
Example – DTD for a Stereo System............................................................................ 75
XML Schema for a Stereo System................................................................................ 76
DTD and XML Schema Comparison ........................................................................... 77
Invalid XML ................................................................................................................. 78
A Validation Tool ......................................................................................................... 79
Example – Validating Stereo Systems.......................................................................... 80
Creating Schema with Visual Studio ............................................................................ 83
Using the Schema Graphical Editor.............................................................................. 87
Lab 3A .......................................................................................................................... 88
Validating XML Streams.............................................................................................. 89
Validation Settings........................................................................................................ 90
Validation Flags ............................................................................................................ 91
.NET Validation Code .................................................................................................. 93
Validation Events.......................................................................................................... 95
Lab 3B........................................................................................................................... 96
Summary ....................................................................................................................... 97
Chapter 4 Writing XML Streams in .NET............................................................... 103
Writing XML in .NET ................................................................................................ 105
The XmlWriter Class .................................................................................................. 106
WriteMovie Example.................................................................................................. 108
The XmlTextWriter Class........................................................................................... 109
The State of Writer...................................................................................................... 110
Creating XmlWriters in .NET 2.0............................................................................... 111
Lab 4A ........................................................................................................................ 112
Writing Out Elements ................................................................................................. 113
Writing Nested Elements ............................................................................................ 115
Writing Attributes ....................................................................................................... 116
Lab 4B......................................................................................................................... 118
Summary ..................................................................................................................... 119
Chapter 5 The Document Object Model in .NET .................................................... 127
The Document Object Model (DOM)......................................................................... 129
Origins of the DOM .................................................................................................... 130
DOM2 Structure.......................................................................................................... 131
DOM Tree Model ....................................................................................................... 132
Tree Model Example................................................................................................... 133
.NET DOM Classes .................................................................................................... 134

Rev. 2.1 Copyright © 2006 Object Innovations viii


All Rights Reserved
The XmlDocument Class............................................................................................ 135
The XmlNode Class – Basic Parsing .......................................................................... 137
Polymorphic Node Types ........................................................................................... 138
The XmlNode Class – Node Types ............................................................................ 139
Example – Walking the Child List.............................................................................. 140
Example – A Recursive Tree Walk ............................................................................ 141
Basic Parsing............................................................................................................... 143
Basic Parsing Example ............................................................................................... 144
Lab 5A ........................................................................................................................ 146
The XmlElement Class ............................................................................................... 147
The XmlAttribute Class .............................................................................................. 148
The XmlAttributeCollection Class ............................................................................. 149
The XmlText Class ..................................................................................................... 150
Lab 5B......................................................................................................................... 151
The XmlNodeList Class.............................................................................................. 152
Using a foreach Loop.................................................................................................. 153
Another Attribute Example......................................................................................... 154
Validation.................................................................................................................... 155
Lab 5C......................................................................................................................... 156
Summary ..................................................................................................................... 157
Chapter 6 Manipulating XML Information with the DOM ................................... 167
Modifying Documents ................................................................................................ 169
Build A DOM Tree – Demo ....................................................................................... 170
The XmlNode Class – Modifications ......................................................................... 174
Legal and Illegal Modifications .................................................................................. 175
Managing Children ..................................................................................................... 176
Cloning........................................................................................................................ 177
Modifying Elements.................................................................................................... 178
Splitting Text and Normalizing .................................................................................. 179
Modifying Attributes .................................................................................................. 180
Lab 6 ........................................................................................................................... 181
Summary ..................................................................................................................... 182
Chapter 7 Using XML Schema.................................................................................. 189
Validating XML Documents....................................................................................... 191
Limitations of DTDs ................................................................................................... 192
What is an XML Schema? .......................................................................................... 193
The XML Schema Recommendation.......................................................................... 194
Schema vs. DTDs........................................................................................................ 195
Schema and Namespaces ............................................................................................ 196
The Schema Namespaces............................................................................................ 197
Structure of a Schema ................................................................................................. 198
Schema Documents..................................................................................................... 199
Associating Documents with Schema......................................................................... 200
Developing a Content Model ...................................................................................... 201
Types of Types............................................................................................................ 202
Types of Types – Diagram.......................................................................................... 203

Rev. 2.1 Copyright © 2006 Object Innovations ix


All Rights Reserved
XML Schema Tools.................................................................................................... 204
Case Study – Movie Listings ...................................................................................... 206
Demo – A Basic Schema ............................................................................................ 207
Defining Elements ...................................................................................................... 211
Defining Complex Types............................................................................................ 212
Demo – A Basic Schema (Resumed).......................................................................... 213
Lab 7A ........................................................................................................................ 216
Attributes..................................................................................................................... 217
Multiple Cardinality.................................................................................................... 218
DTD versus XML Schema.......................................................................................... 220
Constraining Value Ranges......................................................................................... 221
Anonymous Types ...................................................................................................... 222
Lab 7B......................................................................................................................... 223
Schema Object Model................................................................................................. 224
Validate Schema Tool................................................................................................. 225
Validation Code .......................................................................................................... 226
Summary ..................................................................................................................... 227
Chapter 8 XML Serialization .................................................................................... 233
Serialization in .NET .................................................................................................. 235
Serialization Demonstration........................................................................................ 236
CLR Serialization........................................................................................................ 237
Circular List and XML Serialization .......................................................................... 240
XML Serialization Demo............................................................................................ 241
XML Serialization Infrastructure................................................................................ 246
What Will Not Be Serialized ...................................................................................... 247
XML Schema .............................................................................................................. 248
XSD Tool .................................................................................................................... 249
A Sample Schema ....................................................................................................... 250
The XML Designer ..................................................................................................... 251
A More Complex Schema........................................................................................... 252
A Car Dealership......................................................................................................... 253
Deserializing According to a Schema......................................................................... 254
Sample Program.......................................................................................................... 255
Type Infidelity ............................................................................................................ 256
Example – Serializing an Array.................................................................................. 257
Example – Serializing an ArrayList............................................................................ 260
Customizing XML Serialization ................................................................................. 262
Lab 8A ........................................................................................................................ 263
XML Serialization and Web Services......................................................................... 264
ArrayList Web Service Example ................................................................................ 265
Lab 8B (Optional) ....................................................................................................... 266
Summary ..................................................................................................................... 267
Chapter 9 XML and ADO.NET ................................................................................ 273
ADO.NET ................................................................................................................... 275
ADO.NET Architecture .............................................................................................. 276
.NET Data Providers................................................................................................... 278

Rev. 2.1 Copyright © 2006 Object Innovations x


All Rights Reserved
DataSet Architecture................................................................................................... 279
Why DataSet? ............................................................................................................. 280
DataSet Components................................................................................................... 281
DataAdapter ................................................................................................................ 282
DataSet Example Program.......................................................................................... 283
Filling a DataSet ......................................................................................................... 284
Accessing a DataSet.................................................................................................... 285
ADO.NET and XML .................................................................................................. 286
Rendering XML from a DataSet................................................................................. 287
XmlWriteMode ........................................................................................................... 288
Demo: Writing XML Data.......................................................................................... 289
Writing Data as Attributes .......................................................................................... 291
Reading XML into a DataSet...................................................................................... 293
Demo: Reading XML Data......................................................................................... 294
DataSets and XML Schema ........................................................................................ 296
Demo: Writing XML Schema..................................................................................... 297
CourseSchema.xsd ...................................................................................................... 298
Reading XML Schema................................................................................................ 299
XmlReadMode............................................................................................................ 300
Demo: Reading XML Schema.................................................................................... 301
XML Data in DataTables............................................................................................ 303
Typed DataSets ........................................................................................................... 304
Table Adapter.............................................................................................................. 305
Demo: Creating a Typed DataSet Using Visual Studio.............................................. 306
Demo: Creating a Typed DataSet ............................................................................... 309
Synchronizing DataSets and XML ............................................................................. 311
Using XmlDataDocument........................................................................................... 312
Lab 9 ........................................................................................................................... 314
Summary ..................................................................................................................... 315
Chapter 10 XPath ....................................................................................................... 319
Addressing XML Content........................................................................................... 321
XPath........................................................................................................................... 322
The XSLT/XPath Console .......................................................................................... 323
Using the XPath Console ............................................................................................ 325
The XML InfoSet........................................................................................................ 327
XPath Tree Structure................................................................................................... 328
Example – A Simple Tree........................................................................................... 329
Document Order.......................................................................................................... 330
XPath Expressions ...................................................................................................... 331
Context........................................................................................................................ 332
Context Example......................................................................................................... 333
XPath Grammar, From the Top .................................................................................. 334
Decomposing an Expression....................................................................................... 335
Location Paths............................................................................................................. 336
Axis, Node Test, and Predicate................................................................................... 337
Example – Finding the Bank Balance......................................................................... 338

Rev. 2.1 Copyright © 2006 Object Innovations xi


All Rights Reserved
The Axis...................................................................................................................... 339
The Node Test............................................................................................................. 340
The Predicate .............................................................................................................. 341
Abbreviations.............................................................................................................. 342
Using Abbreviations ................................................................................................... 343
XPath Functions.......................................................................................................... 344
XPath and .NET .......................................................................................................... 345
XPath and XmlNode ................................................................................................... 346
Example – SelectNodes()............................................................................................ 347
XPathNavigator........................................................................................................... 350
Evaluate Method ......................................................................................................... 351
XPathNodeIterator ...................................................................................................... 352
XPathNavigator Example ........................................................................................... 353
Lab 10A ...................................................................................................................... 357
XPathNavigator Class in .NET 2.0 ............................................................................. 358
XPathNavigator Example ........................................................................................... 359
Another XPathNavigator Example ............................................................................. 364
Lab 10B....................................................................................................................... 367
Summary ..................................................................................................................... 368
Chapter 11 Introduction to XSLT............................................................................. 375
The Strange Ancestry of XSLT .................................................................................. 377
Input and Output ......................................................................................................... 378
Rule-Based Transformation ........................................................................................ 379
Stylesheets and Transforms ........................................................................................ 380
Applying a Transform to a Document ........................................................................ 381
Referencing a Stylesheet............................................................................................. 382
Templates.................................................................................................................... 383
XSLT Tools and Setup................................................................................................ 384
Using the XSLT Console ............................................................................................ 385
Example – Three Transforms...................................................................................... 388
XSLT and XPath......................................................................................................... 395
Some More Examples ................................................................................................. 396
Style Sheets in the Browser ........................................................................................ 397
A Style Sheet for Browser Display............................................................................. 398
Browser Display.......................................................................................................... 400
XSLT in the .NET Framework ................................................................................... 401
New XSLT Processor ................................................................................................. 402
Sample Program.......................................................................................................... 403
Lab 11 ......................................................................................................................... 404
Summary ..................................................................................................................... 405
Chapter 12 XML Performance Tradeoffs ................................................................ 409
XML Performance ...................................................................................................... 411
Performance Measurements........................................................................................ 412
Measurement Example................................................................................................ 413
Instrumenting an Application ..................................................................................... 415
Instrumentation Example ............................................................................................ 416

Rev. 2.1 Copyright © 2006 Object Innovations xii


All Rights Reserved
Instrumentation Walkthrough ..................................................................................... 417
Implementation Code.................................................................................................. 423
XmlWriter versus the DOM........................................................................................ 425
Validating vs. Non-Validating Readers ...................................................................... 426
Validating Reader Performance Demo ....................................................................... 427
Lab 12 ......................................................................................................................... 430
XSLT Performance ..................................................................................................... 431
XSLT Performance Demo .......................................................................................... 432
Summary ..................................................................................................................... 434
Appendix A Zenith Courseware Case Study............................................................ 437
Appendix B Learning Resources ............................................................................... 451

Rev. 2.1 Copyright © 2006 Object Innovations xiii


All Rights Reserved
Rev. 2.1 Copyright © 2006 Object Innovations xiv
All Rights Reserved
XmlCs Chapter 1

Chapter 1

.NET Framework XML


Overview

Rev. 2.1 Copyright © 2006 Object Innovations 1


All Rights Reserved
XmlCs Chapter 1

.NET Framework XML Overview

Objectives

After completing this unit you will be able to:


• Describe the role of parsing in XML applications.
• Identify the three main parsing APIs in .NET, and
describe the major differences between them.
• Describe the major .NET Framework XML classes.
• Describe XML serialization and its role throughout
the Framework.
• Discuss the close relationship between XML and
ADO.NET.
• Describe XPath and XSLT and the .NET Framework
support for these XML technologies.

Rev. 2.1 Copyright © 2006 Object Innovations 2


All Rights Reserved
XmlCs Chapter 1

XML

• The eXtensible Markup Language, or XML, has


become a very popular choice for a wide array of
software applications:
− Traditional web applications enhanced with XML as an
HTML transformation source
− XML as a portable format for data exchange and archiving
− Business-to-business messaging and Web Services
− Many more

• It is surprising when learning the language how much


can be accomplished using XML and related
standards and generic, pre-built tools, without any
traditional application code.
− XML Stylesheet Language for Transformations, or
XSLT, enables moderately sophisticated document
transformation.
− Modern web browsers can present XML documents to users
with the aid of XSLT, XSL, or Cascading Style Sheets
(CSS), even including hyperlinks with the help of XLink.
− Detailed document structure and content validation can be
effected using XML Schema and a validating parser.

Rev. 2.1 Copyright © 2006 Object Innovations 3


All Rights Reserved
XmlCs Chapter 1

Parsing XML

• At some point, however, the information in XML


documents must be available to application code.
• At its most basic, the process by which an application
reads the information in an XML document is known
as parsing the document.
− Clearly, the literal meaning of the term refers to the gritty
work of reading the document as a stream of characters, and
interpreting that stream according to XML grammar.
− Stated another way, the parsing task might be seen as that of
abstracting the document content – often called its
information set or infoset – from its lexical representation in
XML proper.
− This information set can then be read by application code,
using any number of possible models.
− Document validation can also be performed as part of
parsing.

• All these jobs are quite complex, but, thanks to the


design of XML, also generic.
• Thus individual business applications do not have to
write their own parsing code, instead leveraging
prebuilt packages that offer APIs to their parsing
capabilities.

Rev. 2.1 Copyright © 2006 Object Innovations 4


All Rights Reserved
XmlCs Chapter 1

Using XML in .NET Applications

• Microsoft is a big proponent of XML and is a huge


participant in the W3C.
• The .NET Framework has many areas which are
enabled for XML processing.
− Database queries can be returned in an XML format with
XML Schema definitions.
− Many configuration files in .NET projects are stored in XML
format.
− Web Services uses the XML based SOAP protocol to
remotely call objects on a server.
− The Universal Description, Discovery, and Integration
(UDDI) service uses XML to request and return data to
clients.

• XML support is built into the .NET Framework


• The many different types of .NET applications utilize
services provided in the Framework.
− The XML services we are going to look at includes .NET
classes that interact with the CLR.

Rev. 2.1 Copyright © 2006 Object Innovations 5


All Rights Reserved
XmlCs Chapter 1

The Core .NET XML Namespaces

• The System.Xml namespace and its subsidiary


namespaces encapsulate the XML functionality in the
.NET Framework.
− They contain the classes that parse, validate, traverse, and
create XML streams.
− The namespace classes support the following W3C XML
standards.
XML 1.0 and XML namespaces XML schemas
XPath XSLT
DOM level 1& 2 core SOAP 1.2 (object serialization)

• The System.Xml namespace contains the essential and


major classes for reading and writing.
• The System.Xml namespace contains four subsidiary
namespaces.
− System.Xml.Schema – this namespace contains the XML
classes that provide support for XML Schemas definition
language (XSD) schemas.
− System.Xml.Serialization - classes that are used to serialize
objects into XML streams. The primary class is
XMLSerializer.
− System.Xml.XPath - contains the XPath parser and
evaluation engine for querying XML data streams.
− System.Xml.Xsl – these classes support the Extensible
Stylesheet Transformation (XSLT).

Rev. 2.1 Copyright © 2006 Object Innovations 6


All Rights Reserved
XmlCs Chapter 1

The .NET XML Classes

• The parent class for the nodes found in an XML data


stream is called XmlNode.
• Depending upon the specific type of node the
XmlNode class has six derived classes. They are:
− System.Xml.XmlLinkedNode
− System.Xml.XmlAttribute
− System.Xml.XmlDocument
− System.Xml.XmlDocumentFragment
− System.Xml.XmlEntity
− System.Xml.XmlNotation

• Each of the derived classes contains the properties


and methods that are suitable for that type of node.

Rev. 2.1 Copyright © 2006 Object Innovations 7


All Rights Reserved
XmlCs Chapter 1

.NET XML Classes and Interfaces

• In addition to specifying class hierarchy, the classes


have three interfaces in common:
− ICloneable – Xml nodes can be copied to create a new
instance.
− IEnumerable – Xml nodes support the foreach loop for C#.
− IXPathNavigable – gives the ability to retrieve data from the
node using XPath queries.
− We will use all of these when we start coding.

• Parsers in the System.Xml namespace are found in


several classes.
− XmlTextReader — this class is a fast non-validating
forward-only parser.
− XmlValidatingReader — this parser validates on XML
input using DTDs, Microsoft’s XML-Data Reduced (XDR)
schema, and W3C’s XML Schema definition language
(XSD) schema validation.
− XmlTextWriter — this class provides the methods to assist
you in writing syntactically correct XML. It can write to a
file, stream, console, and other output devices.
− XmlDocument — this class implements the W3C Core
Document Object Model Level 1 and Level 2. It stores the
XML tree in memory and allows you traverse and modify the
nodes.

Rev. 2.1 Copyright © 2006 Object Innovations 8


All Rights Reserved
XmlCs Chapter 1

Parsing Techniques

• There are two traditional methods for parsing XML


streams, and each has advantages and disadvantages.
• The Document Object Model
− The DOM is a W3C standard caching parser and is widely
adopted in many programming environments.
− Good if you need to move forward and backward in the
stream and if you need to modify the node values.
− Bad choice if you’re forward scanning only and not
modifying the document.
− The DOM keeps the entire parsed tree in-memory thereby
consuming computer resources.

• The Simple API for XML (SAX)


− This forward-only non-cached push-model parser allows
applications to process the types of nodes that are of interest.
− This parser uses much less memory than DOM but contains
no representation of the tree. Once a node has been “pushed”
to you your application is responsible for the storing of the
data.
− The filter of node types is static and cannot be changed based
on run-time conditions.
− All node information is pushed to the application and
whether it is requested or not.

Rev. 2.1 Copyright © 2006 Object Innovations 9


All Rights Reserved
XmlCs Chapter 1

.NET Parsing Techniques

• .NET does not support SAX but provides three


different techniques for parsing:
− XML readers and writers
− XML document editing using the DOM
− XML document editing using XPathNavigator

• XML readers provide a more effective read-only,


non-cached, forward-only parser.
− This pull-model parser allows the application to control
parser by specifying which nodes are of interest.
− Saves processing time because only requested nodes are sent
to the application.
− XmlWriter supports generating a stream of XML content.

• The XmlDocument class implements DOM Level 2


functionality.
• XPathNavigator provides an editable, cursor-style
API for reading and editing XML documents.
− In .NET 1.1, this class was read-only, but write capability is
now available with .NET 2.0.
− This model is typically more useable than the DOM
approach.

Rev. 2.1 Copyright © 2006 Object Innovations 10


All Rights Reserved
XmlCs Chapter 1

Parsing Example

• The following code example found in SimpleXML


shows the use of the .NET forward scanning pull-
model non-cached parser.
XmlTextReader tr = new
XmlTextReader("NewCarLot.xml");
Console.WriteLine("XmlTextReader Demo Function");
Console.WriteLine("===========================");
while ( tr.Read() )
{
if ( tr.NodeType == XmlNodeType.Element )
{
Console.Write("Node Name:" + tr.Name);
Console.WriteLine(" Attribute Count:" +
tr.AttributeCount.ToString());
}
}
tr.Close();

• The output of the code is as follows


XmlTextReader Demo Function
===========================
Node Name:Dealership Attribute Count:1
Node Name:Car Attribute Count:0
Node Name:Make Attribute Count:0
Node Name:Model Attribute Count:0
Node Name:Year Attribute Count:0
Node Name:VIN Attribute Count:0
Node Name:Color Attribute Count:0
Node Name:Price Attribute Count:0

Rev. 2.1 Copyright © 2006 Object Innovations 11


All Rights Reserved
XmlCs Chapter 1

How Does SAX and MSXML Fit Into


.NET?

• The MSXML is a COM-based component that is


packaged as a set of COM classes and interfaces.
− The current version of MSXML is 6.0 and is now called
“Microsoft XML Core Services Component Version 4.0.” It
was released on January, 2006.
− This component is still used in VB6 applications.
− MSXML 6.0 can be used by any COM-aware programming
language, including VB6, C++, and VBScript.
− It is possible to use MSXML 6.0 in .NET but the resulting
code is messy.
− When programming in the .NET Framework, the XML
classes are a fundamental feature and support is not an add-
on anymore.
− Using the .NET Framework classes for your XML needs will
make your code faster and easier to use.

• Microsoft discourages the use of SAX in C#


applications because its forward-only, pull model,
non-cached parsing scheme is more efficient and
easier to code.

Rev. 2.1 Copyright © 2006 Object Innovations 12


All Rights Reserved
XmlCs Chapter 1

XmlReader and XmlWriter Features

• XmlReader and XmlWriter are the base classes that


allow you to work with an XML stream.
• Because these are base classes, you can create your
own custom Reader or Writer classes to access the
XML stream.

System.Object

XmlWriter XmlReader

XmlTextWriter XmlTextReader

XmlNodeReader

XmlValidatingReader

• The XmlReader class represents .NET’s forward-only


read-only pull-model XML parser.
− This class provides checks for well-formed XML but not
validation.
− Support XML 1.0 and XML namespaces W3C standards.
− Contains the methods to navigate through document nodes,
and retrieve element and attribute values.

Rev. 2.1 Copyright © 2006 Object Innovations 13


All Rights Reserved
XmlCs Chapter 1

XmlReader and XmlWriter Features

• The XmlTextReader, XmlNodeReader and


XmlValidatingReader classes are derived from
XmlReader class.
− These classes provide different implementation for parsing
your XML streams, as we’ll see later.

• The XmlWriter class has the properties and methods


to create a well-formed and valid XML stream.
− You’ll find a multitude of WriteXXX functions such as
WriteAttributes, WriteStartDocument, WriteNode, etc.

Rev. 2.1 Copyright © 2006 Object Innovations 14


All Rights Reserved
XmlCs Chapter 1

XmlTextWriter Demo

• In this demo we create the XML file that we read in


earlier code. This code is found in the SimpleXML
project.
XmlTextWriter tw =
new XmlTextWriter("NewCarLot.xml", null);
tw.Formatting = Formatting.Indented;
//Opens the document
tw.WriteStartDocument();
//Write comments
tw.WriteComment("A lot of cars!");
//Write first element
tw.WriteStartElement("Dealership");
tw.WriteAttributeString("name", "Cars R Us");

tw.WriteStartElement("Car");
//Write the Make of the Car element
tw.WriteStartElement("Make");
tw.WriteString("AMC");
tw.WriteEndElement();

//Write one more element


tw.WriteStartElement("Model");
tw.WriteString("Pacer");
tw.WriteEndElement();
//... Shortened for brevity
tw.WriteStartElement("Price");
tw.WriteString("3998.99");
tw.WriteEndElement();

tw.WriteEndElement(); // end of car


tw.WriteEndElement(); // end of dealership
tw.WriteEndDocument();
tw.Close(); // close writer

Rev. 2.1 Copyright © 2006 Object Innovations 15


All Rights Reserved
XmlCs Chapter 1

XmlTextWriter Demo (Cont’d)

• This demo creates the “NewCarLot.xml” file in the


SimpleXml directory.
− To make XML files easy to find, we often adjust the project
settings so that the executable will be built in the source
directory, and we keep XML files there too.
<?xml version="1.0"?>
<!--A lot of cars!-->
<Dealership name="Cars R Us">
<Car>
<Make>AMC</Make>
<Model>Pacer</Model>
<Year>1977</Year>
<VIN>CZ7821</VIN>
<Color>Blue</Color>
<Price>3998.99</Price>
</Car>
</Dealership>

Rev. 2.1 Copyright © 2006 Object Innovations 16


All Rights Reserved
XmlCs Chapter 1

.NET DOM Parser Features

• The XmlReader and XmlWriter classes aren’t resource


demanding but they lack the ability to move around
or modify the XML stream.
• The XmlDocument class is resource intensive because
it stores the parsed XML internally offering you the
advantages to navigate, modify, or create the data.
• The downside is the resources used on the machine
will be proportional to the size of the entire XML
stream you’ve read or are creating.
• The DOM is a language-independent W3C
specification; Microsoft’s XmlDocument class
implementation has many of the same property and
methods (with some extensions).
• The XmlNode class, like the DOM Node interface,
specifies the basic functionality for the different types
of nodes in an XML stream.

Rev. 2.1 Copyright © 2006 Object Innovations 17


All Rights Reserved
XmlCs Chapter 1

XmlDocument Demo

• The following code, found in the SimpleXML project


in the method ParseWithTheDOM, reads the XML file
created in the previous demo. This code uses the
DOM parser with the XmlNode class.
XmlDocument doc = new XmlDocument();
doc.Load("newCarLot.xml");

XmlNode root = doc.DocumentElement;


XmlNodeList list = root.SelectNodes("//*");
foreach ( XmlNode elem in list )
{
Console.WriteLine( elem.Name);
}

• The output is:


Dealership
Car
Make
Model
Year
VIN
Color
Price

Rev. 2.1 Copyright © 2006 Object Innovations 18


All Rights Reserved
XmlCs Chapter 1

Demo – Testing Parser Features

• We’ll now work through a simple demonstration of


instantiating and querying the XmlTextReader parser
for some of its features.
− The demo code is in and under Demos\ParserTest —do your
work in this directory. The starting code is backed up in
ParserTest.
− This will also present an opportunity to prove the
environment and tools setup for your machine.
1. Start Visual Studio.
2. Load project ParserTest.sln.
3. Open form Form1.cs.

Rev. 2.1 Copyright © 2006 Object Innovations 19


All Rights Reserved
XmlCs Chapter 1

Demo – Testing Parser Features

4. Examine the code in doXmlReaderParserTest. It asks the


XmlTextReader parser what features it supports, by calling
methods and properties.
XmlTextReader r = new XmlTextReader("CarLot.xml");
r.MoveToContent();
textBox1.AppendText("Can Resolve Entities: " +
r.CanResolveEntity.ToString() +
Environment.NewLine);

textBox1.AppendText("Read State: " +


r.ReadState.ToString() +
Environment.NewLine);

textBox1.AppendText("End of File: " +


r.EOF.ToString() +
Environment.NewLine);

textBox1.AppendText("Current encoding " +


r.Encoding.ToString() +
Environment.NewLine);

textBox1.AppendText("Current xml:lang scope: " +


r.XmlLang.ToString() +
Environment.NewLine);

textBox1.AppendText("Current xml:space scope: " +


r.XmlSpace.ToString() +
Environment.NewLine);

Rev. 2.1 Copyright © 2006 Object Innovations 20


All Rights Reserved
XmlCs Chapter 1

Demo – Testing Parser Features

5. Run the application using F5 and check out result from


doXmlReaderParserTest.

6. Now, what have we just learned? By default the parser will not
resolve entities; it is in an interactive read state; the parser is not
at the end of the file; the encoding is UTF8; language is
English; and the parser will preserve whitespace.

Rev. 2.1 Copyright © 2006 Object Innovations 21


All Rights Reserved
XmlCs Chapter 1

Demo – Testing Parser Features

7. What about the DOM? Take a look at doDOMParserTest:


void doDOMParserTest()
{
label1.Text = "DOM Parser Properties";

XmlDocument oDomParser = new XmlDocument();


bool hasFeature;

hasFeature = oDomParser.Implementation.HasFeature(
"XML", "1.0");
textBox1.AppendText( "XML 1.0 : " +
hasFeature.ToString() + Environment.NewLine);
hasFeature = oDomParser.Implementation.HasFeature(
"XML", "2.0");
textBox1.AppendText( "XML 2.0 : " +
hasFeature.ToString() +
Environment.NewLine) ;
}

8. Remove the comment before doDOMParserTest, and place a


comment before doXmlReaderParserTest. Then Run the
project. The result from doDOMParserTest shows the DOM
parser is created successfully.

Rev. 2.1 Copyright © 2006 Object Innovations 22


All Rights Reserved
XmlCs Chapter 1

Other XML Features in .NET

• XML serialization converts the state of an object into


an XML byte stream suitable for persisting or
transporting.
− .NET supports XML serialization in the namespace
System.Xml.XmlSerialization.

• The foundation of XML serialization is XML


Schema, which is a W3C Recommendation.
− XML Schema is a complete type system.
− .NET supports reading and writing XML Schema in the
namespace System.Xml.Schema.

• ADO.NET is tightly coupled to XML.


− You can exchange both data and schema information
between XML and DataSets.
− Support is provided in the System.Data namespace.
− Classes such as DataSet have explicit methods for working
with XML data.

• XPath provides a mechanism to query for content in


an XML document.
− .NET support is provided in System.Xml.XPath.

• XSLT enables transformation of XML into text,


HTML or other XML.
− .NET support is provided in System.Xml.Xsl.
Rev. 2.1 Copyright © 2006 Object Innovations 23
All Rights Reserved
XmlCs Chapter 1

XML and the Web

• A major motivation for the development of XML was


to support Web applications.
• Both XML and HTML are based on SGML, which
was quite complex.
− HTML is quite simple, but is only concerned with
presentation. Also, although similar to XML, it does not
conform to precise XML syntax.
− XML is also simple and is concerned with the information
content of a document without regard to presentation.
− XHTML is a markup language understood by modern
browsers that is HTML with precise XML syntax.

• A robust way to manage complex information in a


Web site is through XML, with transformation to
HTML as needed for presentation.
− XSLT is an XML technology that supports transformation of
XML to HTML and other formats through a stylesheet.
− There are many other ways to integrate XML with a Web
site, including its use in data management, configuration, and
Web services.

Rev. 2.1 Copyright © 2006 Object Innovations 24


All Rights Reserved
XmlCs Chapter 1

Internet Explorer and XML

• The basic Microsoft Web tool is the Internet Explorer


Web browser.
• It will display well-formed XML in a collapsible tree
view.

• Through a style sheet it can format XML.

Rev. 2.1 Copyright © 2006 Object Innovations 25


All Rights Reserved
XmlCs Chapter 1

Summary

• XML parsing is the cornerstone of .NET Framework


application development. Many higher-level
application capabilities can make use of XML
enabled features:
− Cached/Non-cached, push model, syntax/validating type
parsers available
− XML object serialization
− XML messaging, for instance using SOAP

• Also, there are a number of XML-related


specifications that define their own “languages,” or
really their own XML vocabularies – examples are
XSLT and XML Schema.
− Each of these allows some information to be defined in an
XML document: an XSLT style sheet or transform, an XML
Schema.
− Because these each leverage basic XML, the style sheets and
schema can themselves be parsed and manipulated, just like
any other XML document.

• Microsoft provides the XML functionality, thereby


allowing .NET compliant programming languages to
share the same XML parsing engine.
• XML is tightly integrated with ADO.NET.

Rev. 2.1 Copyright © 2006 Object Innovations 26


All Rights Reserved

You might also like