Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆

680 Project 7 CREATING WEB SERVICES

in-memory, cached tree representation of an XML document that enables the navigation and modification to a document, including adding, updating, or deleting content of elements. The DOM represents data as a hierarchy of object nodes.

At the top of the hierarchy lies the XML document. To implement XML DOM, the .NET Framework provides a set of classes that enable you to access the XML data programmatically included in the System.Xml namespace. Some of the

 

 

 

 

 

Y

classes in the System.Xml namespace are as follows:

 

 

 

 

L

XmlDocument. Represents a complete XML document. XmlDocument

 

 

 

 

F

 

provides a means to view and manipulate the nodes of the entire XML

 

document. The XmlDocument class has the System.Xml.XmlDocument

 

namespace.

 

M

 

 

 

 

A

 

XmlDataDocument. Enables you to store and manipulate XML and

 

relational data into a dataset. This class is derived from the XmlDocument

 

class.

 

E

 

 

 

T

 

 

XmlDocument ype. Represents the DTD used by an XML document.

XmlNode. Supports methods for performing operations on the document as a whole, such as loading or saving an XML file.

XmlTextReader. Represents a reader that performs a fast, noncached, forward-only read operation on an XML document.

XmlTextWriter. Represents a writer that performs a fast, noncached, forward-only generation of streams and files that contain XML data.

XmlElement. Represents a single element from an XML document.

XmlAttribute. Represents a single attribute of an element.

XmlNode and XmlDocument have methods and properties to do the following:

Access and modify nodes specific to a DOM, such as attribute nodes, element nodes, entity reference nodes, and so on.

Retrieve entire nodes, as well as the information the node contains, such as the text in an element node.

There are two other classes that are widely used with XML implementations. These are the XmlReader class and the XmlWriter class. I will first discuss the Xml-

Reader class.

The XmlReader class is an abstract base class that provides noncached, forwardonly, read-only access to XML data. The XmlReader class reads a stream or an XML document to check if the document is well made, and generates XmlExcep-

Team-Fly®

INTRODUCTION TO WEB SERVICES

Chapter 22

681

 

 

 

 

tions if an error is encountered. The XMLReader class implements namespace requirements documented as recommendations by the W3C.

Since the XMLReader class is an abstract base class, it enables you to customize your own type of reader or extend the functionality of current implementations of other

derived classes, such as XmlTextReader, XmlValidatingReader, and XmlNode-

Reader classes.

XMLReader has various properties and methods associated with it. It has methods to read XML content and extract data from complete XML documents, such as XML text files, skip over elements and their content, such as unwanted records, determine whether an element has content or is empty, determine the depth of the XML element stack, and read attributes of elements.

XmlReader has properties that return information, such as the name of the current node and the content of the current node.

Implementations of XmlReader enhance the base class functionality to extend support to various situational requirements. The common implementations of XMLReader can offer fast access to data without validation or complete data validation. The following list describes some implementations of XmlReader:

XmlTextReader. This class reads data extremely fast. It is a forwardonly reader that has methods that return data on content and node types. It has no DTD or schema support.

XmlNodeReader. This class provides a parser over an XML DOM API, like the XmlNode tree. It takes in an XmlNode as a parameter and returns all nodes that it finds in the DOM tree. It has no DTD or schema validation support but it can resolve entities defined in DTD.

XmlValidatingReader. This class provides a fully compliant validating or nonvalidating XML parser with DTD, XML Schema Definition (XSD) language schema, or XML-Data Reduced Language (XDR) schema support.

Custom XML readers. These readers allow developer-defined derivations of the XmlReader.

I will now discuss the XmlWriter class.

XmlWriter is also an abstract base class and it defines an interface for creating XML documents. The XmlWriter class provides a forward-only, read-only, noncached way of generating XML streams, which help you to build XML documents that conform to the W3C and Namespace recommendations.

682 Project 7 CREATING WEB SERVICES

The XmlWriter class has methods and properties that allow you to create wellmade XML documents, specify whether the XML document should support namespaces, write multiple documents to one output stream, manage the output, determine the progress of the output and close the output, report the current namespace prefix, and write valid and qualified names.

However, the XmlWriter class does not check for invalid element and attribute names, Unicode characters that do not match the encoding, and duplicate attributes.

The XmlWriter class has one implementation, the XmlTextWriter class.

Figure 22-3 illustrates the objects that make up the DOM.

FIGURE 22-3 The XML DOM class hierarchy

INTRODUCTION TO WEB SERVICES

Chapter 22

683

 

 

 

 

Extensible Stylesheet Language Transformations (XSLT)

The basic aim of XML is to describe structured data; its focus is not on the presentation of data. XML documents do not contain any tags that define the format of the data to be displayed. This has its advantages and help XML documents remain platform independent. However, you can apply any format to the data and display the same data in multiple formats by using special stylesheets.

W3C has specified a stylesheet called Extensible Stylesheet Language Transformations (XSLT) that is specifically designed for XML documents. The goal of XSLT is to transform the content of a source XML document into another document that is different in format or structure, such as transforming an XML document into HTML to display it in Web applications. In the .NET Framework, the XslTransform class, found in the System.Xml.Xsl namespace, is an XSLT processor that implements the functionality of this specification. To create an XSL stylesheet in the .NET Framework, you use the XSL or XSLT file in the Add New Item dialog box. For example, the following code defines a stylesheet named Employees.xslt for the Employees.xml document:

<xsl:stylesheet version=”1.0” xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” xmlns=”http://www.w3.org/TR/xhtml1/strict”>

<xsl:output method=”xml” encoding=”iso-8859-1” /> <xsl:template match=”/”>

<OL>

<xsl:for-each select=’Employees/Employee’> <LI>

<b>

Employee Id :

<xsl:value-of select=’Id’ /> <br />

</b>

Last Name :

<xsl:value-of select=’LastName’ /> <br /> First Name :

<xsl:value-of select=’FirstName’ /> <br /> <hr />

</LI> </xsl:for-each>

</OL>

</xsl:template>

</xsl:stylesheet>

684 Project 7 CREATING WEB SERVICES

In the preceding code:

The <xsl:template> element allows you to create a template to display the data in the required format.

The <xsl:for-each> element is used to perform a task repeatedly.

The <xsl:value-of> element is used to retrieve the data from individual elements.

After you create the XSLT file, include this file with your XML file to apply the format. To do this, open the Employees.xml file in XML view and, after the first line, add the following line:

<?xml-stylesheet type=”text/xsl” href=”Employees.xslt”?>

When you browse the Employees.xml file in a browser, notice that the output looks formatted.

XSLT uses XPath to select parts of an XML document that are to be formatted. XPath is a query language used to navigate nodes of an XML document tree.

The following is a list of classes commonly used when working with XSLTrans-

form and XPath:

XPathNavigator. An API that provides a cursor-style model for navigating over a data store. To edit the store, you need to use the XmlDocument class.

IXPathNavigable. An interface that provides a CreateNavigator

method to an XPathNavigator for the data store.

XmlDocument. Enables editing of a document. It implements IXPathNavigable to allow editing of document scenarios where XSLT transformations are subsequently required.

XmlDataDocument. A subclass of the XmlDocument class. It bridges the relational database and XML worlds by using a DataSet to optimize storage of structured data within the XML document according to specified mappings on the DataSet. It implements the IXPathNavigable class to allow document scenarios where XSLT transformations can be performed over relational data retrieved from a database.

XPathDocument. Provides a performance cache to optimize XslTransform processing and XPath queries. It implements IXPathNavigable.

INTRODUCTION TO WEB SERVICES

Chapter 22

685

 

 

 

 

XPathNodeIterator. Provides navigation over an XPath nodeset. All XPath selection methods on the XPathNavigator return an XPathNode-

Iterator. Multiple XPathNodeIterators can be created over the same store, each representing a selected set of nodes.

XML Schemas

The XML Schema Definition (XSD) language enables you to define the structure and data types for XML documents. To understand the concept of schemas, I would again like to draw a comparison with a database system. You might know about database schemas that define and validate the tables, columns, and data types that make up the database. Like database schemas, XML schemas also define and validate the content and structure of XML documents and can be used to maintain consistency among various XML documents. XML schema files have the .xsd extension.

But DTDs are also used to define the structure of XML documents. The question that arises here is: how are XML schemas different from DTDs? XML schemas are not really different from DTDs; they only offer a greater functionality. XML schemas can be considered to be supersets of DTDs. XML schemas offer the following advantages over DTDs:

DTDs help you specify whether an element can be empty or can contain character data or other elements. In contrast, XML schemas enable you to specify whether an element can contain an integer, float, or string value.

Unlike DTDs, which have their own syntax, XML schemas use the XML syntax, so you don’t have to learn a new syntax to create XML schemas.

XML schemas contain attribute and element declarations and type definitions for elements. Two basic types of elements can be declared: simpleType and complexType. These element types can be used to define custom data types in addition to the built-in data types provided by XSD, such as integer and string. These two data types can be defined as follows:

simpleType. A type definition for a value that can be used as the content (textOnly) of an element or attribute. This data type cannot contain other elements or have attributes.

686 Project 7 CREATING WEB SERVICES

complexType. A type definition for elements that contain elements and attributes. This data type can contain elements and have attributes.

The element declarations in a schema define the elements, their contents, and attributes that can be used, as well as the rules for their appearance in an XML document that uses the defined schema. An element declaration can contain

either a simpleType or complexType element.

If elements and attributes are defined within the complexType element, the number of elements can be controlled. You can use the minOccurs and maxOccurs attributes to define the number of occurrences of an element in an XML document based on the schema.

The following list describes the elements with XSD:

all. Allows the elements in the group to appear (or not appear) in any order in the containing element.

any. Enables any element from the specified namespace(s) to appear in

the containing complexType, sequence, all, or choice element.

anyAttribute. Enables any attribute from the specified namespace(s) to appear in the containing complexType element.

annotation. Defines an annotation.

appinfo. Specifies information to be used by applications within an annotation element.

attribute. Declares an attribute.

attributeGroup. Groups a set of attribute declarations so that they can be incorporated as a group into complex type definitions.

choice. Allows one and only one of the elements contained in the group to be present within the containing element.

ComplexContent. Contains extensions or restrictions on a complex type that contains mixed content or elements only.

complexType. Defines a complex type, which determines the set of attributes and the content of an element.

documentation. Specifies information to be read or used by users within the annotation element.

element. Declares an element.

extension. Contains extensions on complexContent or simpleContent,

which can also extend a complex type.

INTRODUCTION TO WEB SERVICES

Chapter 22

687

 

 

 

 

field. Specifies an XML Path Language (XPath) expression that specifies the value (or one of the values) used to define an identity constraint (unique, key, and keyref elements).

group. Groups a set of element declarations so that they can be incorporated as a group into complex type definitions.

import. Identifies a namespace whose schema components are referenced by the containing schema.

include. Includes the specified schema document in the target namespace of the containing schema.

key. Specifies that an attribute or element value (or set of values) must be a key within the specified scope.

keyref. Specifies that an attribute or element value (or a set of values) corresponds with the value of the specified key or unique element.

list. Defines a simpleType element as a list of values of a specified data type.

notation. Contains the definition of a notation.

redefine. Allows simple and complex types, groups, and attribute groups that are obtained from external schema files to be redefined in the current schema.

restriction (XSD). Defines constraints on a simpleType, simpleContent,

or complexContent definition.

schema. Contains the definition of a schema.

selector. Specifies an XPath expression that selects a set of elements for an identity constraint (unique, key, and keyref elements).

sequence. Requires the elements in the group to appear in the specified sequence within the containing element.

simpleContent. Contains either the extensions or restrictions on a complexType element with character data, or contains a simpleType element as content and contains no elements.

simpleType. Defines a simple type element, which determines the constraints on and information about the values of attributes or elements with text-only content.

union. Defines a simpleType element as a collection of values from specified simple data types.

688 Project 7 CREATING WEB SERVICES

unique. Specifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope.

The Schema Object Model (SOM) provides a set of classes in the System.Xml.Schema namespace that is fully compliant with the W3C XML Schema recommendation specifications. These classes allow you to programmatically create a schema in memory that you can compile and validate.

The SOM provides the following features:

Loads and saves valid XSD language schemas to and from files.

Provides an easy way to create memory-resident schemas using strongly typed classes.

Interacts with the XmlSchemaCollection class to cache and retrieve schemas.

Interacts with the XmlValidatingReader class (through the XmlSchemaCollection class) to validate schemas against XML documents.

Enables developers to build editors for creating and maintaining schemas.

XML in .NET

The class XPathNavigator is the main XML class that is used with .NET. You can specify an XPath query to XPathNavigator so that it returns an iterator. This iterator will represent the nodeset that is returned from the query you specified. You can use the XPathNavigator class to move through XML documents by using commands, such as MoveToNext().

XPathNavigator accepts the file name and path of a file on the disk and loads the file for processing. However, the case is different with .NET. Since .NET is stream-based, the XmlReader class reads XML streams. However, you cannot use XmlReader directly and require using a derived class, because XMLReader is an abstract class. Similarly, .NET provides the XMLWriter class, which is used for writing XML data. Just like XmlReader, XMLWriter is also an abstract class that can be implemented by using a derived class. .NET provides the class XmlTextWriter for this purpose.

Web Services and SOAP

As mentioned earlier, Web services interact with other applications by using XML. SOAP is a protocol that is used in these types of interactions for invoking

INTRODUCTION TO WEB SERVICES

Chapter 22

689

 

 

 

 

Web services. SOAP was developed by Microsoft and Userland Software with the goal to provide a mechanism for exchanging information in a structured format among computers in a distributed environment.

SOAP is considered a simple and light mechanism, primarily for the following two reasons:

SOAP enables you to receive an acknowledgement from the destination. This ensures better performance of SOAP-based applications because the security and coordination aspects are automatically taken care of.

SOAP uses XML, which is a text-based format.

Besides being light and simple, SOAP offers another advantage through its ability to overcome firewalls. You might already know that firewalls are basically configured to block ports with dynamically assigned port numbers. Since SOAP uses port number 80 (that is assigned to HTTP), it is able to pass through firewalls easily.

Though by name, SOAP suggests that the underlying Web service representation is an object, that is not necessarily the case. SOAP provides the standard Remote Procedure Call (RPC) mechanism that is aimed at carrying information on a local computer to a remote computer. SOAP exchanges application data in the XML format over various protocols, such as HTTP and FTP. The parameter values of a remote method are interpreted at run time and these values are filled into an XML document. The HTTP protocol then transfers this data to the remote server.

Though SOAP consists of XML elements, you can think of these elements as objects such that each object has a specific purpose. This SOAP object model consists of the following objects:

SOAP Envelope. The primary function of this object is to convey XML namespace information when the SOAP XML packet was serialized. This object is also responsible for encapsulating SOAP information for SOAP RPC invocations.

SOAP Header. The primary function of this object is to transmit information that is relevant to the Web service processing that is not a part of the method signature. The SOAP Header is an optional object. Thus, it is possible that you do not find header information serialized in a SOAP packet.