Using the XML Classes in VB. NET

Many organizations use XML to pass documents and data within the organization as well as between trading partners and vendors. Due to the ubiquitous nature of these exchanges, sooner or later developers will need to read and write XML documents, transform them with XSL, and validate them using XML schemas. In this article, Dan Fox discusses the support in the Services Framework for working with XML in these ways.

This article is excerpted from Chapter 13, "Integrating with the Enterprise," from Building Distributed Applications with VB.NET, by Dan Fox (ISBN 0672321300). This material is based on the Beta2 release version of Microsoft's .NET technology.

From the author of

From the author of

This articles assumes that the reader has some experience with VB, the Windows
environment, event-based programming, basic HTML, and scripting.

As is obvious by now, XML is ingrained in .NET from configuration and files
to the protocol for Web Services to acting as the data store for ADO.NET DataSet
objects. Of course, these particular uses of XML highlight its self-describing
and flexible nature. As a result, many organizations use XML to pass documents
and data both within the organization and between trading partners and vendors.
The ubiquitous nature of these exchanges means that sooner or later, developers
will need to read and write XML documents, transform them with XSL, and validate
them using XML schemas. This section will discuss the support in the Services
Framework for working with XML in these ways.

At the highest level, the classes used to manipulate XML in the Services Framework
are included in the System.Xml namespaces shown in Table 13.1.

Table 13.1—XML Namespaces and their uses.

Namespace

Description

System.Xml

Contains the core XML classes to read and write XML documents and map
the document to the Document Object Model (DOM).

System.Xml.Schema

Contains classes to work with XSD schemas and validate documents.

System.Xml.Serialization

Contains objects that enable classes to be serialized to XML.

System.Xml.XPath

Contains classes that allow you to navigate XML documents using XPath.

System.Xml.Xsl

Contains classes that allow you to transform documents using XSL stylesheets.

Developers familiar with working with XML documents in the COM world will
no doubt have used the MSXML parser to programmatically manipulate documents.
For those developers, the System.Xml classes will seem familiar because
they both map to the DOM and because System.Xml was modeled after
MSXML. However, the Services Framework implementation includes better standards
compliance and a simpler programming model (especially for streamed access)
that should make life easier. That being said, you can continue to use MSXML
through COM Interop, although I think you'll find that porting code that
works with the DOM will be relatively simple, while rewriting code that uses
SAX, the Simple API for XML introduced in MSXML 3.0, will make for a more
straightforward and efficient application.

To give you an overview of how the System.Xml namespace provides standards-based
support for working with XML, this discussion will include dealing with streamed
access to XML documents, manipulating XML documents with the DOM, handling XML
schemas, and using XML serialization.

Streamed Access

Perhaps the biggest innovation in the System.Xml namespace, and the
way in which you'll typically interact with XML documents, is through the
use of a stream-based API analogous to the stream reading and writing performed
on files discussed in Chapter 11. At the core of this API are the
XmlReader and XmlWriter classes, which provide read-only,
forward-only cursor access to XML documents and an interface for writing out XML
documents, respectively. Since these class implement a stream-based approach,
they do not require that the XML document be parsed into a tree structure and
cached in memory as happens when working with the document through the DOM.

Using an XML Reader

When the DOM was first published and vendors such as Microsoft began writing
parsers like MSXML to read those documents, it became immediately apparent that
the programming model was not ideal for all applications. This was particularly
the case when the XML document was large, since by definition the DOM represents
the entire document in an in-memory tree structure. Not only did performance
suffer using the DOM since you had to wait for the document to be parsed and
loaded, but the application processing the document tended to eat up significant
amounts of memory. As a result, Microsoft included the SAX APIs in MSXML 3.0 to
provide an event-driven programming model for XML documents. While this
alleviated the performance and memory constraints of the DOM, it did so at the
cost of complexity.

The XmlReader implementation is in many ways a melding of the DOM
and SAX and provides a simplified programming model like the DOM but in a
stream-based architecture. The programming model is simplified because it is a
pull rather than a push model. In other words, developers pull data from the
document using a familiar cursor-style looping construct rather than simply
being pushed data by responding to events fired from the parser.

The XmlReader class is actually an abstract base class for the
XmlTextReader, XmlValidatingReader, and XmlNodeReader
classes. The XmlReader is often used as the input or output arguments
for other methods in the Services Framework. A typical use of the
XmlTextReader is to read XML produced from the FOR XML statement in SQL
Server 2000 and then load a DataSet object as shown in the following
code:

Note that the ExecuteXmlReader method of the SqlCommand
object returns an XmlReader which is then accepted as an argument to
one of the overloaded ReadXml methods of the DataSet object.
As discussed in Chapter 7, the second argument to the ReadXml method
specifies how the XML is parsed using one of the XmlReadMode
constants.

As implied by the names, XmlTextReader simply provides a reader that
checks for well-formedness of an XML document and any inline DTDs but does not
perform validation using an associated DTD or schema as does
XmlValidatingReader. As a result, XmlTextReader is the fastest
way to parse an XML document using a file, Stream, or
TextReader as input. XmlNodeReader, on the other hand, can
parse XmlNode objects from an XML DOM subtree, as will be discussed
later. To give you a feel for the readers, the important members or the
XmlTextReader class are shown in Table 13.2.

Table 13.2—Important XmlTextReader members.

Member

Description

AttributeCount

Returns the number of attributes on the current node

BaseURI

Returns the base URI used to resolve external references to the current
node

Depth

Returns the depth of the current node within the XML document

EOF

Returns True if the XmlReader is positioned at the
of the stream

HasAttributes, HasValue

Returns True if the current node has attributes or a value

IsDefault

Returns True if the attribute of the current node was generated
from the default specified in the DTD or schema

IsEmptyElement

Returns True if the current node is an empty element

Item

Indexed property that returns an attribute from the current node

LineNumber, LinePosition

Returns current location information

LocalName, Name

Returns the name of the current node without the namespace prefix and
the qualified name, respectively

NodeType

Returns the XmlNodeType for the current node

ReadState

Returns the state of the XmlReader using one of the ReadState
constants (Closed, EndOfFile, Error, Initial,
Interactive)

Value

Returns the value of the current node as a String

Namespaces, NamespaceURI

Specifies whether to support namespaces and the namespace of the current
node, respectively

WhitespaceHandling

Specifies how to parse whitespace encountered in the document

Close

Closes the document and changes the ReadState to Closed

GetAttribute

Returns the value of the attribute given the index or name. If it does
not exist, return an empty string

GetRemainder

Returns that part of the document still in the buffer as a TextReader
object

IsStartElement

Returns True if the current node is a start tag. Also overloaded
to accept an element name that first navigates to the next content element
using MoveToContent

In this example, the ExtractStudents method uses the overloaded
constructor of the XmlTextReader class to pass in the name of a file.
In addition, the XmlReader exposes an XmlNameTable in the
NameTable property that is used to store frequently used strings. By
using a name table, the XML parser can reuse the strings in the table when
returning element names and can use more efficient object pointer comparisons
when doing comparisons. An existing XmlNameTable can also be passed
into the constructor so that comparison across readers will also be more
efficient.

If the file can be opened a DoLoop is used to iterate
through the contents of the document using the Read method, which
returns False upon reaching the end of the stream.

One of the interesting aspects of an XmlReader is that the Read
method not only returns each tag (begin and end elements, processing
instructions, CDATA sections, comments, and document type definitions) but also
whitespace. And as you might imagine, it does so in a recursive way such that an
entire element including all of its children is processed before moving on to a
sibling element. The type of the current node can be checked using the
NodeType property.

In order to more efficiently move through the document, you can use the move
methods such as MoveToContent, as in this example.
MoveToContent skips over any processing instructions, DTDs, comments,
and whitespace and moves to the next CDATA section, beginning or ending element,
or entity reference.

As mentioned previously, the XmlTextReader will only make sure the
document is well-formed and will otherwise throw an XmlException. In
this example, both the Read method and the MoveToContent
methods may generate the exception since both perform navigation. Note also that
once a well-formedness error is encountered, the ReadState of the
XmlTextReader is set to Error and no more processing on the
document can be performed.

TIP

By logging the LinePosition of the error, as is done here, the
method could be easily altered to re-process the document starting with the
appropriate line.

NOTE

You can also skip only the whitespace by setting the
WhiteSpaceHandling property to the None constant of the
WhiteSpaceHandling enumeration.

The element name can then be checked using the Name property before
proceeding to read the value of the element using the Value property or
one of the read methods shown in Table 13.2.

TIP

In this example, the Depth property is used to ensure that the
method only processes top-level Student elements by checking for a depth of
1.

However, you'll notice in this case that the data for the student is
actually contained in attributes of the Student element. Attributes are not
represented as separate nodes by XmlReader, but rather as a collection
associated with the node. As a result, attributes are typically accessed using
the Item property or the GetAttribute method. Alternatively, the
MoveToAttribute method can be used to position the cursor over the
attribute passed to the method, and the Name and Value
properties are set to the name of the attribute and its value. The collection
can also be navigated in this way using the MoveToFirstAttribute and
MoveToNextAttribute methods.

The values are then extracted from the attributes and passed to a method that
saves them in the database.

An advanced technique that XmlReader supports, shown in Listing
13.1, is the optional expansion of entity references. Simply put, an entity
reference allows an XML document to be compressed by defining an entity once in
a document and referencing it multiple times like so:

When the XmlReader encounters the expression "&2073,"
the NodeType will be set to EntityReference. By invoking
ResolveEntity, the substitution will occur and processing will continue
with the CourseNum and CourseDesc elements. Note that XmlTextReader,
however, does not support entity referencing, and the CanResolveEntity
property can be used to determine whether entities can be resolved.

To perform validation against an XML document, you can associate an
XmlValidatingReader object with an XmlTextReader. The
XmlValidatingReader exposes a Schemas collection
(XmlSchemaCollection) that contains one or more schemas (DTDs, XSD,
XDR) represented as XmlSchema objects that can be used to validate the
document. Validation errors are then reported through a
ValidationEventHandler. The Validate method in Listing 13.2
shows the basics of validating a document using an XDR schema.

Listing 13.2. Validating XML. This method shows how to validate a document
against a schema.

Note that the XmlValidating reader is initialized with the
XmlTextReader and the schema added through the Add method of
the XmlSchemaCollection. The arguments represent the namespace URI (as
it is referred to in the document to be validated) and the URL of the schema to
load. The event handler where errors will be reported is created using the
AddHandler statement, in this case pointing to the
ValidationError method. The schemas must be added to the collection
before the Read method is called. The ValidationType property
is set to the XDR constant of the ValidationType enumeration.

TIP

By setting the ValidationType property to None, validation
will be bypassed. However, it is more efficient to simply use the
XmlTextReader if validation is not required.

As an alternative to creating the XmlSchemaCollection on the fly, as
shown in Listing 13.2, you can create a stand-alone XmlSchemaCollecton
object and, when needed, pass it to the Add method of the
Schemas property. In this way, the schemas are only loaded once. This
allows multiple documents to be loaded without re-loading and re-parsing the
schemas.

Using an XML Writer

Not only does System.Xml provide streamed access for reading
documents, it also includes the XmlWriter class for high-performance
output. Once again, the XmlWriter class is the base class, while you
typically work with the XmlTextWriter derived class.

Basically, the XmlTextWriter includes properties that allow you to
control how the XML will be written in terms of its formatting and namespace
usage, methods analogous to other stream writers discussed in Chapter 11 such as
Flush and Close, and a bevy of Write methods that add
text to the output stream. The important members for the XmlTextWriter
class are shown in Table 13.3.

Table 13.3—Important XmlTextWriter members.

Member

Description

Formatting

When set to Formatting.Indented, specifies that output will
be formatted according to the Indentation and IndentChars
properties

Indentation

Specifies how many IndentChar characters to write out for each
level in the hierarchy. Default is 2

IndentChars

Specifies which character to use for indentation

Namespaces

When set to True, namespaces are supported

QuoteChar

Specifies which character to use to quote attribute values

WriteState

Set to one of the WriteState enumeration constants (Attribute,
Closed, Content, Element, Prolog,
Start)

Close

Closes the XmlTextWriter and the underlying stream

Flush

Flushes whatever is in the buffer for the XmlTextWriter and
the underlying stream

LookupPrefix

Returns the closest prefix defined in the current namespace scope

WriteAttributes

Writes out all the attributes found at the current position in the XmlReader

WriteAttributeString

Writes an attribute with the specified value

WriteBase64, WriteBinHex, WriteChars, WriteString

Write the given argument to the underlying stream using the appropriate
data type

The interesting aspect of the XmlTextWriter class is
that it abstracts all of the formulation and writing of tags that would
typically have to be done if you were creating an XML document manually. In
fact, the XmlTextWriter is smart in that it keeps track of the
hierarchy of the document in order to automatically providing ending tags
through methods such as WriteEndElement and WriteEndDocument.
The result is a programming model that not only performs very well, but is also
extremely simple to use.

To illustrate the use of the XmlTextWriter class, consider the
WriteXml method shown in Listing 13.3.

Listing 13.3. Writing XML. This simple method accepts a text file as an
argument and writes it out as an XML document.

In this example, you'll notice that a text file containing student
information is passed into the WriteXml method and is opened using a
standard FileStream object. The XmlTextWriter is initialized
with the name of the XML document to write to in addition to the encoding to
use. The overload constructor also accepts Stream or
TextWriter objects.

As indicated in Table 13.3, the formatting for the document is specified
using the Formatting and Indentation properties. The header of
the document, along with a comment, is then written using the
WriteStartDocument and WriteComment methods. The
WriteStartElement method writes out the Students element and includes a
namespace declaration. As implied by the name, this method writes out the
beginning of the tag but does not yet close it.

The DoLoop reads through each line of the text file (which
in this case is a fixed-format file) and parses its contents into four variables
that include the student's ID, name, and organization. To write out the
meat of the data, a Student element is created using WriteStartElement
and its attribute using WriteAttributeString. Note that both of these
methods can also accept namespace and prefix information. A child element to
contain the name is then created by invoking WriteStartElement again.
Its attributes are then also created. At this point, two elements have been
created but have not been closed. The WriteEndElement method determines
the current context and writes the appropriate ending tag (either a
"/>" or a full ending tag that includes the element name). In this
case, it will simply close the Name tag since it does not contain a value.

If the organization is present, the WriteElementString method is
used to write a complete element including its closing tag along with the value
passed to the method. The Student tag is then closed once again using the
WriteEndElement method.

Once the input file has been exhausted, the XML document is finished off by
writing the ending tag for the Students element using WriteEndDocument.
This method also tracks the current context and closes any open elements. The
file is closed by calling Flush followed by Close, as is
typical of stream writers.