Web Services using .
NET
XML
Institute of Systems Science
National University of Singapore
© 2004 ISS. The contents contained in this document may not be reproduced in any form or by any means, without the written permission of ISS, other than for the purpose for which it has been supplied.
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Total Pages: 89
Web Services using .NET
Agenda
Module objectives
To understand how XML works for Web Services
Module topics
Whatand Why XML?
XML structure
¾ Elements, attributes, namespace
XSL,XSD, DOM, SAX
XML data island
XML in .NET Framework
¾ System.Xml
¾ XmlNode, XPathNavigator, XmlReader, XmlWriter
¾ XmlValidatingReader, XmlDataDocument
¾ System.Xml.Serialization, XmlSerializer
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 2
© 2004 ISS. All rights reserved
Web Service Layers
XML Define web service data values
XSD Define web service types
SOAP Encode web service message call
WSDL Describe web services
UDDI Discover web services
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 3
© 2004 ISS. All rights reserved
What is XML?
XML is eXtensible Markup Language
XML is a standard text based format for exchanging content
¾ A tag-based markup language and a meta language
XML is an open W3C standard
¾ http://www.w3.org/TR/REC-xml
XML is widely used for document/data
¾ Text documents with tags to annotate
¾ Hierarchical data structures
<?xml version="1.0" encoding="utf-8"?>
<string xmlns=“http:/tempuri.org/”>
Hello World
</string>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 4
© 2004 ISS. All rights reserved
Sample XML for Data
Employee data in database
Binary format would not look like this
“Benjamin Gan”
16 May, 1997
“Associate”
$1,000.00
XML representation in text
<Employee>
<Name>Benjamin Gan</Name>
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position>
<Salary>$1,000.00</Salary>
<Bonus/>
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 5
© 2004 ISS. All rights reserved
Why use XML?
Richly structured text based document
Yet, it is simple and flexible
Open W3C standards
Ubiquitous on the internet
Use by all major IT corporation
Technology Independent
Highlyinteroperable across applications, languages and platforms
Work on multiple transport protocol: Http, Smtp, Ftp, email, etc
Self-describing meta data (connection-less)
Allow loosely coupled programming
¾ Interoperability without connected end points
¾ Discovery of remote services and capabilities
Suitable for mobile connections
¾ Such as PDA, smartphones, tablet PC, …
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 6
© 2004 ISS. All rights reserved
XML is Everywhere
Client Application Server
WebService
Database
Configuration
Documents
Repository SmartPhones
Data PDA
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 7
© 2004 ISS. All rights reserved
Weaknesses of XML
Text based
Inefficient
storage format compared to binary
Performance overhead for transmission
No fixed tag semantics
Tag interpretations are domain specific and semantics may clash
¾ Standards are needed for domain specific semantics (eg bioinformatics)
XML original intent is for document exchange
Specification for distributed computing is not complete
¾ No standard for transactions, objects, security, etc
¾ WSA, GXA, ebXML, etc are working on WS-Transaction, WS-Security, etc
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 8
© 2004 ISS. All rights reserved
XML Structure
XML is a mark-up language for content
XML is like HTML (but for content instead of presentation)
¾ Unlike HTML, XML does not define standard semantics for its tags
¾ With HTML, XML allows documents to separate presentation from content
¾ XML is a subset of SGML, HTML is an implementation of SGML
XML defines a hierarchical structure (tree) for data
¾ The data can be words, images, operations, parameters, …
¾ The data is self describing based on domain defined tags
What is XML document?
XML documents are composed of markup and content
XML processors/parsers are used to read XML documents
¾ They help applications access the XML document content and structure
¾ DOM and SAX provide a standard API for the XML processors/parsers
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 9
© 2004 ISS. All rights reserved
XML Document Markups
What is XML Document Content?
Content are character data defined as all text that is not markup
What is XML Document Markup?
Markup in XML documents are delimited by < > or &
¾ For example, <string> represents <string>
¾ If the markup characters are needed, they can be escaped using numeric
character references or the strings “&” and “<”
Element markups (tags)
¾ The tag name usually identify the nature of the content it surround
<string>Hello World</string>
Comment markups
¾ Comments may appear anywhere in a document outside other markup
<!-- Here are the comments -->
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 10
© 2004 ISS. All rights reserved
XML Document Markups
Processing instructions markups
¾ This is an escape hatch to provide information to an application
<?xml version="1.0" encoding="utf-8"?>
CDATA sections markup
¾ This markup instructs the parser to ignore markup characters (< or &)
<![CDATA[ b = ( i < 3); ]]>
Document type declarations (DTD) markups
¾ DTD places constraints on the XML structure
¾ DTD support the use of predefined storage units (predefined types)
¾ DTD contains markup declarations that provide a grammar for the document
<!DOCTYPE greeting [<!ELEMENT greeting (#PCDATA)>]>
<greeting>Hello, world!</greeting>
¾ Markup declarations can be placed on element types, attribute list, entities
and notations
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 11
© 2004 ISS. All rights reserved
XML Elements
Element Markups (tags)
Each element has a begin and end tag names
¾ Tag names are case sensitive [a..z, A..Z, _]{a..z, A..Z, 0..9, _, -, ., :}*
¾ Tag names beginning with “xml” are reserved
<TagName>Hello World</TagName>
Elements can be empty <Bonus></Bonus> <Bonus/>
Elements are serialized in the order they are defined
Element children are serialized between tags
<Employee>
<Name>Benjamin Gan</Name>
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position> Element
<Salary>$1,000.00</Salary> Children
<Bonus/>
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 12
© 2004 ISS. All rights reserved
XML Attributes
XML attributes describe the XML element
XML attributes are define inside the XML element start tag
XML attributes are define as name and value pairs
¾ The names must be unique within the element
¾ The values must be text only enclosed in “” or ‘’
¾ Attributes are not ordered (serialized order are implementation dependent)
<height units=“inches”>68</height>
<height units=‘cm’>140</height>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 13
© 2004 ISS. All rights reserved
Well-Formed XML Element Rules
Only one root element
Sub-elements must be properly nested
Attributes and processing instructions are optional
XML tag name must be valid and is case-sensitive
Attribute values must be enclosed in “” or ‘’ Case sensitive makes
<parent1> this improperly nested
<child1 attribute”=value”>Child Element</Child1>
<-child2/> Invalid tag name
</parent1>
<parent2> Only one root
<Child1 attribute=value>Child Element</Child1>
</parent2>
Attribute value not enclosed in “” or ‘’
Refer to http://www.w3.org/TR/2000/REC-xml-20001006
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 14
© 2004 ISS. All rights reserved
Why Namespaces?
XML 1.0 does not support namespaces
Namespace is recommended in XML extensions
Namespaces avoid unqualified tag names from clashing
<Employee> NUS <Employee> ISS
<Name>Benjamin Gan</Name> <Name>Benjamin Gan</Name>
<Position>Associate</Position> <Position>Teacher</Position>
</Employee> </Employee>
A qualified tag name is scoped by a namespace
A unique namespace makes the qualified name unique
SOAP uses URI as the namespace identifiers
The purpose for namespace in XML is the same as for other
programming languages (C++, C#, etc)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 15
© 2004 ISS. All rights reserved
Uniform Resource Identifiers (URI)
URI uniquely identify items in the internet (RFC 2396)
Uniform Resource Locators (URL)
¾ URL is the best-known type of URI (RFC 1738)
http://www.ietf.org/rfc
ftp://ftp.ietf.org/rfc
Uniform Resource Names (URNs)
¾ URN may not resolve to a unique, physical location (RFC 2141)
¾ URNs serve as persistent resource identifiers
urn:www.iss.nus.edu.sg:gan:wsnet
urn:uuid:XXXX-XXX-XXX-XXX-XXXXXXXXX
Namespace ID Namespace Specific String
¾ Namespace ID is case-insensitive
¾ Only unique URN should be used as namespace
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 16
© 2004 ISS. All rights reserved
Namespaces
The namespace scope is specified using a prefix (qualifier)
Prefixed Qualified Name Namespace declaration Attribute Namespace Identity
<Namespace:ElementName xmlns:namespace=“URI”>
Content
</ElementName>
XML documents from different authors can be merged
<NUS:Employee xmlns:NUS=“http://www.nus.edu.sg/hr”>
<Name>Benjamin Gan</Name>
<NUS:Position>Associate</NUS:Position>
NUS
</NUS:Employee>
<ISS:Employee xmlns:ISS=“urn:www.iss.nus.edu.sg-gan-wsnet”>
<Name>Benjamin Gan</Name>
<ISS:Position>Teacher</ISS:Position>
ISS
</ISS:Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 17
© 2004 ISS. All rights reserved
Default Namespace
Declare a namespace without a prefix
<Employee xmlns=“urn:www.iss.nus.edu.sg-gan-wsnet”>
<Name>Benjamin Gan</Name> Unqualified sub elements take the
<Position>Teacher</Position> declared namespace “urn:www.iss…”
</Employee>
Name without a prefix are called unqualified name
All unqualified elements take the declared namespace by default
¾ All unqualified sub-elements take the default namespace
¾ If no namespace is declared, all unqualified elements have no namespace
All unqualified attributes does not take the default namespace
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 18
© 2004 ISS. All rights reserved
Namespace Scope
Namespace scoping for unqualified elements
The inner-most default namespace supercedes outer namespaces
<Employee xmlns=“urn:www.iss.nus.edu.sg-gan-wsnet”>
<Name xmlns=“http://www.nus.edu.sg/hr”> Inner namespace
<Lastname>Gan</Lastname> Lastname uses NUS
</Name>
Outer namespace
<Position>Teacher</Position>
Position uses ISS
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 19
© 2004 ISS. All rights reserved
Character Encoding
XML serializes in a specific character encoding
Supported encodings
UTF-8,UTF-16, US-ASCII, Shift_JIS, ISO-8859-1
Use UTF-8 for XML with predominately Latin characters
Use UTF-16 for XML with predominately far eastern characters
<?xml version=‘1.0’ encoding=‘UTF-16’ ?>
<Employee xmlns=“urn:www.iss.nus.edu.sg-gan-wsnet”>
<Name xmlns=“http://www.nus.edu.sg/hr”>
<Lastname>Gan</Lastname>
</Name>
<Position>Teacher</Position>
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 20
© 2004 ISS. All rights reserved
XML Extensions
XSLT/XSL RDF
XSL style sheet specifies the presentation Resource description framework for
of XML documents describing and interchanging metadata
XSLT transform information from one DOM
vocabulary to another API to read, create and edit XML
XPath document (via in-memory object)
Syntax for building addresses to the SAX
information found in an XML document Simple API for XML
XML schema definition/XSD API to parse XML documents
Define the schema that map XML Provide event driven notification
documents to programming language types XML protocol
(superset to DTD)
Peer communications in a distributed
XLink environment (XML messaging using
Describes links between resources using serialization for RPC)
elements in XML documents (complex XML RPC, SOAP, XMI, ebXML, jabber,
links) WSDL, UDDI, DISCO, …
XPointer XUL
Based on XPath, it allows for traversals of XML-based User Interface Language. It is
a document tree used for specifying user interfaces of
XML query applications. It works across platforms as
Query facilities to extract data from long as XUL can be rendered.
documents on the web (interaction to the
database world)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 21
© 2004 ISS. All rights reserved
Transformations: XSL and XSLT
XSL style sheet
XSL specifies the presentation of XML documents
XSL consist of XSLT, XPath and XSL Formatting Objects
XSLT
XSLT transform information from one vocabulary to another
XSLT describes how to transform the document using templates
¾ The transformer matches pattern nodes in source file to be mapped into the
result format in the destination file
in.xml
out.xml
in.xsl
XML transformer
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 22
© 2004 ISS. All rights reserved
XML Schema Definition (XSD)
Defines schema that can be mapped to prog. lang. types
It adds type to a XML document Type/Schema
Instance <complexType name=“Person”>
<person id=“S1234567A”> <sequence>
<name>Benjamin Gan</name> <element name=“name” type= “string”/>
<element name=“birthdate” type= “date”/>
<birthdate>1985-01-01</birthdate> </sequence>
</person> <attribute name=“id” type=“NRIC”/>
</complexType>
XML Document Programming Language
XML Instance Object
Schema Type Class
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 23
© 2004 ISS. All rights reserved
Defining Datatypes in XML
Possible candidates to define types for XML documents
Use Document Type Definitions (DTD)
¾ SOAP 1.1 does not use DTD in SOAP message
¾ The markup declaration (DTD itself) is not written in XML
¾ DTD has no support for data types (only PCDATA) or namespaces
¾ DTD do not specify type information (it uses predefined storage units)
Use XML Data Reduced schema (XDR)
¾ This is an interim schema proposed by Microsoft (replaced by XSD)
XML Schema Definition (XSD)
XSD provides a superset of capabilities found in DTD
¾ XSD can define type information in XML
¾ XSD supports data types (type checking for validity)
XSD is recommended by W3C (Standard)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 24
© 2004 ISS. All rights reserved
DTD and XSD Sample
XML document and its DTD grammar (schema)
<Employee xmlns=“…"> <!DOCTYPE Employee [
<Name>Benjamin Gan</Name> <!ELEMENT Employee (Name, Position+) >
<Position>Teacher</Position> <!ELEMENT Name (#PCDATA) >
</Employee> <!ELEMENT Position (#PCDATA) > ]>
Define the XSD for Employee complex type
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:gan-employee-schema“ elementFormDefault="qualified"
targetNamespace="urn:gan-employee-schema" >
<xsd:element name="Employee" type="EmployeeType" />
<xsd:complexType name="EmployeeType">
<xsd:all>
<xsd:element name="Name" type="xsd:string"/>
<xsd:element name="Position" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
</xsd:schema>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 25
© 2004 ISS. All rights reserved
What is XML Schema?
XSD defines types
XSD defines grammar (rules) for XML document
¾ The grammar places constraints on the XML structure
XSD defines primitive, derived and user defined types
¾ They are mapped to programming language types
XSD defines the data types
¾ XML documents that conforms to the grammar are called valid XML
¾ Valid XML documents are more restrictive than well formed XML
¾ XSD defines the constraints for validating the data types
¾ They verify the overall "correctness" of an XML document
XSD specification is standard organized by W3C
http://www.w3.org/XML/Schema
¾ Part 0: Primer, Part 1: Structures and Part 2: Datatypes
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 26
© 2004 ISS. All rights reserved
Datatypes in XSD
Datatype is based on <value space, lexical space, facets>
Value space is the set of all valid values for a given data type
¾ Values can be primitive, enumerated, derived or composed (union or list)
¾ Values properties can be cardinality, order, equality, etc
Lexical space is the set of text representations of the values
¾ They are the set of valid literals (representation) for a datatype
¾ Eg. The float value space can have 1.00 and 1.0E2 lexical representations
¾ Types with multiple lexical representations have a canonical representation
Facets characterize properties of values or lexical items
¾ Facet distinguishes one datatype from another
¾ Each facet defines an aspect (subset) of the value space
XSD define types to give meaning (type) to the data (XML
document)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 27
© 2004 ISS. All rights reserved
XSD Facets
Facet defines an aspect (subset) of a value space
Thereare 2 types of facets:
Fundamental facet
¾ An abstract property that characterizes the values of a value space
¾ For example, equal, order, bounds, cardinality and numeric
Constraining (non-fundamental ) facet
¾ Optional properties that can apply to a datatype to constrain its value space
¾ For example, length, minLength, maxLength, pattern (regular expression),
enumeration (does not impose order), maxInclusive, maxExclusive,
minInclusive, minExclusive, precision, scale, encoding, duration and period
Type Value Space
Faceted Value Space
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 28
© 2004 ISS. All rights reserved
XSD Constraining Facets Sample
Postcode type with exactly 7 digits
<xs:simpleType name="Postcode">
<xs:restriction base="xs:string">
<xs:length value="7" fixed="true"/> </xs:restriction>
</xs:simpleType>
A negative integer from -100 to -1
<simpleType name="negativeInteger">
<restriction base="xsi:integer">
<minInclusive value="-100" /> <maxInclusive value="-1" />
</restriction>
</simpleType>
Barcode number for products
<simpleType name=“Sku">
<restriction base="string">
<pattern value=“\d{3}-[A-Z]{2}”/> </restriction>
</simpleType>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 29
© 2004 ISS. All rights reserved
Primitive and Derived Datatypes
Primitives are not defined in terms of other types
Eg.Float is well defined, but integer is a special case of decimal
anySimpleType
¾ This is the base type for all primitive types
¾ Its value space is the union of all primitive value space
Derived datatypes are defined in terms of other types
Derived by restriction (using constraining facets)
Derived by list <xs:simpleType name=“posIntUpTo100”>
<xs:restriction base="xs:positiveInteger">
Derived by union
<xs:maxExclusive value="100"/>
</xs:restriction>
</xs:simpleType>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 30
© 2004 ISS. All rights reserved
Atomic, List and Union Datatypes
Atomic are indivisible primitive or derived value
<simpleType name=“decimal”> </simpleType>
List has a finite length sequence of values
<simpleType name=“sizes”>
<list itemType=“integer”/>
</simpleType> <shoeSize xsi:type=“sizes”> 6 7 8 9 </shoeSize>
Union value is any of the member type values
<xsd:element name=“size”>
<xsd:simpleType>
<xsd:union>
<xsd:simpleType><xsd:restriction base=“integer” /></xsd:simpleType>
<xsd:simpleType><xsd:restriction base=“string” /></xsd:simpleType>
</xsd:union>
<size>6</size>
</xsd:simpleType>
<size>large</size>
</xsd:element>
<size xsi:type=“xsd:string”>1</size>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 31
© 2004 ISS. All rights reserved
Build-in Datatypes
Datatypes defined in http://www.w3.org/TR/xmlschema-2/
Each build-in datatypes can be uniquely addressed (URI)
¾ Eg. int is http://www.w3.org/TR/xmlschema-2/#int
Each facet definition can be uniquely addressed (URI)
¾ Eg. maxInclusive is http://www.w3.org/TR/xmlschema-2/#rf-maxInclusive
Namespace for XSD datatypes should refer to
¾ http://www.w3.org/2001/XMLSchema (xsd)
¾ http://www.w3.org/2001/XMLSchema-datatypes
¾ http://www.w3.org/2001/XMLSchema-instance (xsi)
<definitions name="GoogleSearch"
targetNamespace="urn:GoogleSearch"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" …>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:GoogleSearch"> Namespace for
defined schema
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 32
© 2004 ISS. All rights reserved
Datatypes
Built-in Datatypes
Derived Datatypes
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 33
© 2004 ISS. All rights reserved
XSD Definitions: Simple Types
XSD definitions place constraints on value/lexical space
Simple types
They apply constraints on base type or list of other simple types
¾ Simple types work on all the built-in primitive and derived data types
The constraints work on attributes and elements
¾ The elements are text based content with no child elements
Simple types are defined using the simpleType element
¾ Constraints are defined using elements, attributes, and facets
<simpleType name=“strings”>
<list itemType="string”/> <simpleType>
</simpleType> <restriction base="positiveInteger">
<maxExclusive value="100"/>
</restriction>
</simpleType>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 34
© 2004 ISS. All rights reserved
XSD Definitions: Complex Types
Complex types
They define attribute declarations & content model (child element)
¾ Complex types describe structured data
They restricts a complex type or extends a simple/complex type
¾ They extend by adding content or adding attribute declarations
Complex types are defined using the complexType element
¾ The first child nest the content model using
¾ <xsd:sequence>: all children in order of declaration
¾ <xsd:choice>: one of the child
¾ <xsd:all>: all children in any order
XSD declarations describe the content models of elements
A declaration associates a name to a set of constraints
¾ The declarations are not types by themselves, they define the content model
¾ There is a separate definition for the types used within the declaration
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 35
© 2004 ISS. All rights reserved
Complex Types Sample
Complex types contain elements in their content
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/> Declaration describing
<xsd:element ref="comment" minOccurs="0"/> the content models of
<xsd:element name="items" type="Items"/> PurchaseOrderType
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:complexType name="USAddress"> Attribute Declarations
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/> Nested
<xsd:element name="city" type="xsd:string"/> child
<xsd:element name="state" type="xsd:string"/> elements
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN“ fixed="US"/>
</xsd:complexType>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 36
© 2004 ISS. All rights reserved
GoogleSearchResult ComplexType
<definitions name="GoogleSearch" targetNamespace="urn:GoogleSearch"
xmlns:typens="urn:GoogleSearch“ … >
<!– Types -->
Type Namespace
<types>
<xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" Type Schema
targetNamespace="urn:GoogleSearch">
<xsd:complexType name="GoogleSearchResult"> ComplexType Definition
<xsd:all>
<xsd:element name="documentFiltering" type="xsd:boolean"/> …
</xsd:all>
</xsd:complexType>
</xsd:schema></types>
<!-- Messages -->
Type Binding
<message name="doGoogleSearchResponse">
<part name="return" type="typens:GoogleSearchResult"/></message>
<!-- Port -->
<operation name="doGoogleSearch">
<input message="typens:doGoogleSearch"/>
<output message="typens:doGoogleSearchResponse"/></operation>
<!-- Binding --><!-- Endpoint --></definitions>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 37
© 2004 ISS. All rights reserved
Why use XSD?
W3C Standard
Broad support for data types
Reusable “components”
Simpledata types
Complex data types
Extensible
Inheritance support
Namespace support
Ability to map to relational database tables
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 38
© 2004 ISS. All rights reserved
XML Document Object Model (DOM)
DOM provides APIs for manipulating XML documents
DOM is a standard programming model for working with XML
DOM is a core vendor/language-neutral API
DOM includes a set of objects and interfaces
The objects represent the entire XML document in memory
The objects represent the content and structure of the document
¾ For example, elements, attributes, etc
The interface enables a program to load, access, manipulate, and
serialize the XML documents
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 39
© 2004 ISS. All rights reserved
Simple API for XML (SAX)
SAX provides APIs to parse XML documents
The APIs allow developers to read/write XML data
The data is sequentially accessed (not cached)
SAX uses an event driven parsing
¾ A “push” model to parse the XML data
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 40
© 2004 ISS. All rights reserved
DOM and SAX
Similarity
DOM and SAX project the XML document programmatically
¾ SAX can be used to build DOM trees
¾ Developers can traverse DOM trees and emit SAX streams
Differences
SAX sequentially access the XML document
¾ SAX require less memory (smaller input, work and output buffers)
¾ SAX facilitates searching large documents for small pieces of information
¾ SAX can abort processing large documents when task is completed
DOM randomly access the XML document in memory
¾ DOM constructs the data structure in memory
¾ DOM is useful in processing complex queries with contexts
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 41
© 2004 ISS. All rights reserved
Microsoft XML Core Services (MSXML) 4.0
MSXML parser implements DOM specification
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 42
© 2004 ISS. All rights reserved
Microsoft XML Core Services (MSXML) 4.0
MSXML parser implements SAX2 specification
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 43
© 2004 ISS. All rights reserved
HTML with XML Data Islands
Embed “islands” of XML data inside HTML pages
Available
in Internet Explorer 5.0 and later
Follow W3C “XML in HTML Meeting Report”
Use DHTML <XML> element within the HTML document
<xml id="xmlID"> Employee1.html
<Employee>
<Name>Benjamin Gan</Name>
<Position>Associate</Position>
</Employee>
</xml>
¾ The <XML> element can have a SRC attribute to read XML from a file
<XML id="xmlID" src="Employee.xml"> Employee2.html
<XML SRC="http://localhost/Employee.xml"></XML>
The HTML DOM is seen by the browser
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 44
© 2004 ISS. All rights reserved
Access XML Data Using HTML DOM
To access the XML data (via HTML DOM)
The <XML> element can be referenced by ID alone
¾ The documentElement property contains the root element of the document
¾ It defines an IXMLDOMElement interface
¾ It has a read/write property
function GetEmpElement() { Employee1.html
alert( xmlID.documentElement.text);
}
Accessed using the DHTML XMLDocument property
function GetEmpElement() {
var oNode = xmlID.XMLDocument.selectSingleNode("Employee/Name");
alert(oNode.text); <Employee>
} <Name>Benjamin Gan</Name> Employee2.html
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position>
<Salary>$1,000.00</Salary>
<Bonus/> Employee.xml
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 45
© 2004 ISS. All rights reserved
XML Element (Object) Properties
Properties Description
canHaveHTML Value indicating whether the object can contain rich HTML markup
id String identifying the object
isContentEditable Value indicating whether the user can edit the contents of the object
isDisabled Value indicating whether the user can interact with the object
isMultiLine Value indicating whether the object contains one or more lines
parentElement Parent object in the object hierarchy
readyState Current state of the object
recordsetSets Data source object reference to the default record set
scopeName Retrieves the namespace defined for the element
SRCsrcSets Retrieves a URL to be loaded by the object
tagUrnSets Retrieves the URN specified in the namespace declaration
XMLDocument Reference to the XML DOM exposed by the object
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 46
© 2004 ISS. All rights reserved
Traverse the XML Data (via HTML DOM)
Use the childNodes property to traverse the child elements
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
var root;
xmlDoc.async = false; Employee3.html
xmlDoc.load("Employee.xml");
root = xmlDoc.documentElement;
for (var i=0; i<root.childNodes.length; i++) {
alert(root.childNodes.item(i).childNodes.item(0).text);
}
documentElement
Children
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 47
© 2004 ISS. All rights reserved
Binding HTML Table to XML Data
Client-side data binding to XML data island
Thebound elements are updated dynamically as data changes
HTML table element is a tabular data consumer,
¾ Specify the dataSrc attribute to the XML data (eg. xml ID)
¾ Specify the dataFld attribute to the XML element
There are other HTML elements that can be bound to XML data
¾ A, APPLET, BUTTON, FRAME, INPUT, IMG, LABEL, SPAN, …
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 48
© 2004 ISS. All rights reserved
Binding HTML Table to XML Data Sample
<xml ID="xmlID"> Employee4.html
<?xml version="1.0" ?>
<Employees>
<Employee>
<Name>Benjamin Gan</Name>
<Position>Associate</Position>
</Employee>
<Employee>
<Name>Derek Kiong</Name>
<Position>Member</Position>
</Employee>
</Employees>
</xml>
<table datasrc=#xmlID border=1><tr>
<td><div datafld="Name"></div></td>
<td><div datafld="Position"></div></td>
</tr></table> Element
mapping
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 49
© 2004 ISS. All rights reserved
XML in .Net Framework
XML use is ubiquitous throughout .NET
ASP.NET, web services and ADO.NET
XML classes in .Net Framework are built on W3C standards
XML classes are extensible through OO subclassing
XML classes are design for high performance
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 50
© 2004 ISS. All rights reserved
System.Xml Namespace
System.Xml
Serialization
Schema • Contains classes that are
• Provides standards- used to serialize objects
based support for XML into XML format
Schemas (XSD) documents or streams
XPath DOM Xsl
• Contains the XPath • Provides • Provides support for
parser and evaluation standards-based Extensible Stylesheet
engine support for Transformation (XSLT)
• It supports the W3C Document Object transforms
XML Path Language Model (DOM) • It supports the W3C XSL
(XPath) Level 1 & 2 Transformations (XSLT)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 51
© 2004 ISS. All rights reserved
XML DOM Hierarchy (XmlNode)
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 52
© 2004 ISS. All rights reserved
XML DOM Tree Node Sample
<?xml version="1.0" ?> Each node inherits
<Employees> from XMLNode
<Employee> The document is a
<Name>Benjamin Gan</Name> XMLDocument object
<HiredDate>15 May 1997</HiredDate> Nodes have a single
<Position>Associate</Position> parent node
<Salary Currency=“Sing”>$1,000.00</Salary>
<Bonus/>
Most nodes can have
document multiple child nodes
</Employee>
</Employees> Attributes are not
xml Employees nodes
They are properties
XMLElement Employee of the element node
XMLElement
Name HiredDate Position Salary Bonus
XMLText Currency
Benjamin Gan 15 May 1997 Associate $1000 “Sing”
XMLAttribute
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 53
© 2004 ISS. All rights reserved
Load XML Document (via DOM)
public class WebForm1 : System.Web.UI.Page { DOM1/WebForm1.aspx.cs
static private XmlDocument _doc = null;
public XmlDocument doc {
get { if (_doc == null) _doc = new XmlDocument();
return _doc; }
}
private void btnLoadXML_Click(object sender, System.EventArgs e)
{
lbStatus.Text = "Loading ... ";
doc.LoadXml( XmlDocument::LoadXml
"<Employee>" + "<Name>Benjamin Gan</Name>" +
"<HiredDate>15 May 1997</HiredDate>" +
"<Position>Associate</Position>" +
"<Salary Currency='Sing'>$1,000.00</Salary>" +
"<Bonus/>" + "</Employee>");
lbStatus.Text += "Done";
}
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 54
© 2004 ISS. All rights reserved
Load and Save XML Document (via DOM)
private void btnLoad_Click(object sender, System.EventArgs e) {
lbStatus.Text = "Loading ... ";
doc.Load(tbLoadFileName.Text); XmlDocument::Load
lbStatus.Text += "Done";
}
private void btnSave_Click(object sender, System.EventArgs e) {
if (doc.HasChildNodes) {
// Save the document to a file.
lbStatus.Text = "Saving ... ";
// Make sure aspnet_wp has write permission at the directory
doc.Save(tbSaveFileName.Text); XmlDocument::Save
lbStatus.Text += "Done";
} DOM1/WebForm1.aspx.cs
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 55
© 2004 ISS. All rights reserved
Traverse the XML Data (via DOM)
Use the ChildNodes property to traverse the child elements
private void btnDisplay_Click(object sender, System.EventArgs e)
{
if (doc.HasChildNodes) {
XmlElement root = doc.DocumentElement;
lbStatus.Text = "";
for (int i = 0; i < root.ChildNodes.Count; i++) {
if (root.ChildNodes[i].HasChildNodes)
lbStatus.Text += root.ChildNodes[i].Name + ": " +
root.ChildNodes[i].FirstChild.Value + "<br>";
}
}
DOM1/WebForm1.aspx.cs
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 56
© 2004 ISS. All rights reserved
Create XmlNode (via DOM)
Create a XmlElement and append it to the Xml document
private void btnChildElement_Click(object sender,
System.EventArgs e)
{
if (doc.HasChildNodes) {
lbStatus.Text = "Adding employee field ... ";
XmlElement root = doc.DocumentElement;
XmlElement newChildElem =
doc.CreateElement(tbChildElemName.Text);
newChildElem.InnerText = tbChildElemValue.Text;
root.AppendChild(newChildElem);
lbStatus.Text += "Done"; DOM1/WebForm1.aspx.cs
}
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 57
© 2004 ISS. All rights reserved
XPath
DOM (via XmlNode) provides simple traversal
XPath contains a parser and evaluation engine
It
provides a generic navigation mechanism (XPathNavigator)
XPathNavigator access XmlDocument using a cursor model
¾ XPathNavigator provide read only, random access to data
¾ XPathNavigator can select and navigate a subset of a document
¾ XPathNavigator works on other data stores (file systems or databases)
¾ XPathNavigator supports XSLT
System.Xml.XPath supports XPathNavigator
¾ Use IXPathNavigable.CreateNagivator
¾ IXPathNavigable is implemented in XmlNode and XPathDocument
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 58
© 2004 ISS. All rights reserved
XPath Sample Using XPathNavigator
Create a XmlElement and append it to the Xml document
using System.Xml.XPath; // Gan: XmlPathNavigator
…
private void btnXPath_Click(object sender, System.EventArgs e)
{
if (doc.HasChildNodes) {
XPathNavigator nav = doc.CreateNavigator();
nav.MoveToRoot();
nav.MoveToFirstChild(); // Employee
nav.MoveToFirstChild(); // Employee children
lbStatus.Text = "";
do {
lbStatus.Text += nav.Name + ": " + nav.Value + "<br>";
} while (nav.MoveToNext());
} XPath/WebForm1.aspx.cs
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 59
© 2004 ISS. All rights reserved
XmlReader
XmlReader is an abstract class to read XML document
It provides a non-cached, forward-only, read-only access
¾ No edit of attributes or elements
¾ No insert and remove nodes
It uses a “pull” model
¾ Simpler than the SAX “push” model where the parser pushes events
¾ It pulls data from XML or to skip unwanted records at will
It reads in depth-first order (traversal)
¾ Same order as textual XML data
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 60
© 2004 ISS. All rights reserved
Pull (XmlReader) vs Push (SAX) Model
Pull Push
State Management Client simplifies state Requires the content handlers to build
management by a natural, top- very complex state machines
down procedural refinement
Multiple Input Allow the client to put together Complex to do
Streams multiple input streams
Layering The push model can be built on Reverse is not true
top of the pull model
Extra String Copy Allow the client to give the Normally, the data is read from the
Avoidance parser a buffer into which the parser buffer into the string object,
string is directly written which is then pushed to the client buffer
Selective Client can skip items, Notifies the client of each item,
Processing processing only those items that including attributes, processing
are of interest to the application instructions, and white space
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 61
© 2004 ISS. All rights reserved
XmlReader Implementations
XmlTextReader implements XmlReader using XML 1.0
Supports input from streams, strings and TextReader objects
XmlNodeReader implements XmlReader
Reads data from an entire XmlDocument or a specific XmlNode
Access to data via XPathNavigator
XmlValidatingReader implements XmlReader
Provides XSD, XDR and DTD validation while reading
Use the Schemas property for cached schema files
ValidationType property specifies what type of validation
User defined custom reader
Implement XmlReader
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 62
© 2004 ISS. All rights reserved
Load XML data (via XmlTextReader)
XmlTextReader reader = null; PullSAX/WebForm1.aspx.cs
reader = new XmlTextReader(tbLoadFileName.Text);
reader.WhitespaceHandling = WhitespaceHandling.None;
while (reader.Read()) { Element: Employee
Advance read cursor Element: Name
switch (reader.NodeType) {
case XmlNodeType.Element: Text: Benjamin Gan
lbStatus.Text += "Element: " + reader.Name + "<br>"; EndElement:Name
Element: HiredDate
break; Text: 15 May 1997
case XmlNodeType.Text: EndElement:HiredDate
lbStatus.Text += "Text: " + reader.Value + "<br>"; Element: Position
break; Text: Associate
case XmlNodeType.Comment: EndElement:Position
lbStatus.Text += "Comments:" + reader.Value + "<br>";Element: Salary
Text: $1,000.00
break;
EndElement:Salary
case XmlNodeType.XmlDeclaration: Element: Bonus
lbStatus.Text += "XML Declaration<br>"; EndElement:Employee
break;
case XmlNodeType.EndElement:
lbStatus.Text += "EndElement:" + reader.Name + "<br>";
break; } }
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 63
© 2004 ISS. All rights reserved
XmlWriter
XmlWriter is an abstract class to create XML Document
It provides a fast, non-cached, forward-only, write-only creation
It creates a well-formed XML document in a type-safe manner
It serialized data and push it to a stream
XmlTextWriter implements XmlWriter
¾ Supports creation of streams, files and TextWriter objects
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 64
© 2004 ISS. All rights reserved
Writing XML Data (via XmlTextWriter)
XmlTextWriter xwriter = new
XmlTextWriter(tbSaveFileName.Text,System.Text.Encoding.UTF8);
xwriter.WriteStartDocument(true);
PullSAX/WebForm1.aspx.cs
xwriter.WriteStartElement("Employee");
xwriter.WriteElementString("Name", "Benjamin Gan");
xwriter.WriteElementString("HiredDate", "15 May 1997");
xwriter.WriteElementString("Position", "Associate");
xwriter.WriteStartElement("Salary");
xwriter.WriteAttributeString("Currency", "SingDollar");
xwriter.WriteString("$1,000.00");
xwriter.WriteEndElement();
xwriter.WriteStartElement("Bonus");
xwriter.WriteEndElement(); xwriter.WriteEndElement();
xwriter.WriteEndDocument(); xwriter.Close();
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Employee><Name>Benjamin Gan</Name>
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position>
<Salary Currency="SingDollar">$1,000.00</Salary>
<Bonus /></Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 65
© 2004 ISS. All rights reserved
XmlValidatingReader Sample
XmlValidatingReader provides validation while reading
private void btnValidate_Click( … ) { ValidateSAX/WebForm1.aspx.cs
XmlValidatingReader vreader = null;
try {
XmlTextReader reader = new XmlTextReader(tbLoadFileName.Text);
vreader = new XmlValidatingReader(reader);
valid = true;
vreader.ValidationEventHandler +=
new ValidationEventHandler (ValidationCallBack);
vreader.Schemas.Add("urn:gan-employee-schema",tbValidate.Text);
while (vreader.Read()) lbStatus.Text += vreader.Value + "<br>";
if (valid) lbStatus.Text += "Data is valid";
else lbStatus.Text += "Data invalid!";
} finally { if (vreader != null) vreader.Close(); }
}
Called when validation
public void ValidationCallBack ( … ) {
errors occurs
valid = false;
lbStatus.Text +="<br>Validation error: "+args.Message + "<br>"; }
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 66
© 2004 ISS. All rights reserved
XML Schema
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:gan-employee-schema" Elements from the target namespace must
elementFormDefault="qualified" be qualified with the namespace prefix
targetNamespace="urn:gan-employee-schema" >
<xsd:element name="Employee" type="EmployeeType" />
<xsd:complexType name="EmployeeType">
<xsd:all>
<xsd:element name="Name" type="xsd:string"/>
<xsd:element name="HiredDate" type="xsd:date"/>
<xsd:element name="Position" type="xsd:string"/>
<xsd:element name="Salary" type="xsd:decimal"/>
<xsd:element name="Bonus" type="xsd:decimal"/>
</xsd:all>
</xsd:complexType>
</xsd:schema> Employee.xsd
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 67
© 2004 ISS. All rights reserved
XML Data
<?xml version='1.0'?>
<Employee xmlns="urn:gan-employee-schema">
<Name>Benjamin Gan</Name>
<HiredDate>1997-05-15</HiredDate>
<Position>Associate</Position>
<Salary>1000.00</Salary>
ValidEmployee.xml
<Bonus>100</Bonus>
</Employee>
<?xml version='1.0'?>
<Employee xmlns="urn:gan-employee-schema">
<Name>Benjamin Gan</Name>
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position>
<Salary>$1,000.00</Salary>
<Bonus/> InvalidEmployee.xml
</Employee>
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 68
© 2004 ISS. All rights reserved
XmlValidatingReader Reflection
Schema type information can be read at run time
while (vreader.Read()) {
if (vreader.NodeType == XmlNodeType.Element) { Returns
if (vreader.SchemaType is XmlSchemaComplexType) { XmlSchemaType
XmlSchemaComplexType sct = or Datatype
(XmlSchemaComplexType) vreader.SchemaType;
lbStatus.Text += vreader.Name + "(" + sct.Name + ")<br>";
} else {
Returns CLR-typed value
object value = vreader.ReadTypedValue();
mapped from XmlSchemaType
if (value != null)
lbStatus.Text += vreader.Name + "(" + value.GetType().Name
+ ")" + value + "<br>";
}
}
Employee(EmployeeType) ValidateSAX/WebForm1.aspx.cs
Name(String)Benjamin Gan
} HiredDate(DateTime)5/15/1997 12:00:00 AM
Position(String)Associate
Salary(Decimal)1000
Bonus(Decimal)100
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 69
© 2004 ISS. All rights reserved
XML in .Net Framework
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 70
© 2004 ISS. All rights reserved
Workshop: XML Namespace
Objective
We will develop a WinForm client display Xml nodes, changed
namespaces, validate and save the Xml documents
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 71
© 2004 ISS. All rights reserved
.Net XML Class Improves Performance
They support a streaming-based model
XmlReader
¾ Minimal caching for forward-only, pull model parsing
¾ Instead of SAX “push” model
XmlValidatingReader
¾ Forward-only validation
XPathNavigator
¾ Cursor style navigation which minimizes node creation
¾ Random access without a complete node tree in memory like the DOM
XslTransform
¾ Incremental streaming output
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 72
© 2004 ISS. All rights reserved
System.Xml Support for Relational Data
XmlDataDocument
Extends XmlDocument to support relational data (files, RDBMS)
Provide a DataSet property which synchronize with Xml data
Support XSD on the XML data
¾ XSD can be inferred from XML data, loaded and saved
System.Xml provides tight relationship with DataSet
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 73
© 2004 ISS. All rights reserved
XmlDataDocument and DataSet
XmlDataDocument DataSet
Sync
DataTable
SqlConnection SqlDataAdapter
XmlTextReader XmlNodeReader
XmlReader SqlCommand SqlDataReader
SQL Server .NET Data Provider
Xml
Xml
Document
Document SQL Server
7.0+
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 74
© 2004 ISS. All rights reserved
Load XML Document (via XmlDataDocument)
public class WebForm1 : System.Web.UI.Page {
static private XmlDataDocument _doc = null;
public DataSet dataSet {
get { XmlDataDoc/WebForm1.aspx.cs
if (_doc == null) {
_doc = new XmlDataDocument();
_doc.DataSet.Namespace = "XMLTest"; }
return _doc.DataSet;
} }
private void btnLoad_Click(object sender, System.EventArgs e) {
lbStatus.Text = "Loading ...";
FileStream fsReadXml = new FileStream(tbLoadFileName.Text,
FileMode.Open, FileAccess.Read);
XmlTextReader myXmlReader = new XmlTextReader(fsReadXml);
dataSet.ReadXml(myXmlReader);
lbStatus.Text += "Done";
} }
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 75
© 2004 ISS. All rights reserved
Save XML Document (via XmlDataDocument)
private void btnSave_Click(object sender, System.EventArgs e)
{
// Make sure aspnet_wp has write permission at the directory
FileStream fsWriteXml = new FileStream(tbSaveFileName.Text,
FileMode.Create);
XmlTextWriter xmlWriter = new XmlTextWriter(fsWriteXml,
System.Text.Encoding.Unicode);
dataSet.WriteXml(xmlWriter);
fsWriteXml.Close(); XmlDataDoc/WebForm1.aspx.cs
}
<Employee>
<Name>Benjamin Gan</Name>
<HiredDate>15 May 1997</HiredDate>
<Position>Associate</Position>
<Salary>$1,000.00</Salary>
<Bonus />
</Employee> XmlDataDoc/SavedEmployee.xml
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 76
© 2004 ISS. All rights reserved
Traverse the XML Data (via XmlDataDocument)
private void Display(DataSet dataSet) {
lbStatus.Text = "";
foreach(DataTable table in dataSet.Tables) {
lbStatus.Text += "TableName: " + table.TableName + "<br>";
lbStatus.Text += "<table cellspacing='1' border=1><tr>";
foreach(DataColumn column in table.Columns) {
lbStatus.Text += "<td>" + column.ColumnName + "</td>"; }
lbStatus.Text += "</tr>";
foreach(DataRow row in table.Rows) {
lbStatus.Text += "<tr>";
foreach(DataColumn column in table.Columns) {
lbStatus.Text += "<td>" + row[column] + "</td>"; }
lbStatus.Text += "</tr>"; }
lbStatus.Text += "</table>"; } XmlDataDoc/WebForm1.aspx.cs
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 77
© 2004 ISS. All rights reserved
Create DataSet and Return XML
private void btnAdd_Click(object sender, System.EventArgs e) {
DataSet ds = new DataSet("NewDataSet");
DataTable t = new DataTable(tbTableName.Text);
DataColumn c1 = new
DataColumn("id", Type.GetType("System.Int32"));
c1.AutoIncrement= true;
DataColumn c2 = new DataColumn("item");
t.Columns.Add(c1); t.Columns.Add(c2);
ds.Tables.Add(t);
DataRow newRow; XmlDataDoc/WebForm1.aspx.cs
for(int i = 0; i < 10; i++) {
newRow = t.NewRow();
newRow["item"]= "item " + i;
t.Rows.Add(newRow); }
ds.AcceptChanges();
Display(ds);
lbStatus.Text += ds.GetXml();
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 78
© 2004 ISS. All rights reserved
Xml Serialization
Mappings between CLR types and XSD (Not Isomorphic)
System.Xml.Serialization maps XSD to CLR types
System.Runtime.Serialization maps CLR types to XSD
XSD CLR Type
Complex No mapping
Type ???
Complex Complex
Type Class Class
Type
System.Xml.Serialization
Schema Type Class
Complex
System.Runtime.Serialization
Complex
Type Class Class
Type
??? No mapping Class
Not interoperable
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 79
© 2004 ISS. All rights reserved
System.Runtime.Serialization
Handles CLR types (handles complex types not in XSD)
Public and private data
Polymorphism
Collections (but does not handle recursive definition)
How to serialize a CLR type?
Use custom attribute [Serializable] – .Net does the work
[Serialization] public class Employee { … }
Implements ISerializable interface – you do all the work
[Serializable()] public class Employee:ISerializable { … }
Serialization.Formatters controls the formatting of types
IFormatter
interface provides the API for formatting
SoapFormatter which uses standard SOAP layout
The deserializer assumes access to .Net assembly
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 80
© 2004 ISS. All rights reserved
System.Xml.Serialization
Handle XSD (guarantees XSD interoperability)
Publicdata only (properties and fields)
Limited support for polymorphism
Limited support for collections
XmlSerializer class are bound to CLR types
Serializemethod to write an object to an XmlWriter
Deserialize method to read an object from an XmlReader
XmlSerializer generate serialization code into temporary assembly
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 81
© 2004 ISS. All rights reserved
XmlSerializer
XSD CLR Type
XmlSerializationWriter
Code Generated to Temp Assembly
XmlWriter
Serialize
<Employee> public class EmployeeType {
<Name>Benjamin Gan</Name> public string Name;
… XmlSerializer …
</Employee> Complex } Class
Type Deserialize
XmlReader
XmlSerializationReader
Code Generated to Temp Assembly
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 82
© 2004 ISS. All rights reserved
XmlSerializer Serialize & Deserialize
private void btnSerialize_Click(…) {
emp = EmployeeType.NewEmployee();
FileStream fs = new FileStream(tbOutputFileName.Text,
FileMode.Create);
XmlSerializer xs = new XmlSerializer(emp.GetType());
xs.Serialize(fs, emp);
fs.Close(); Serialize/XmlSerialize/Form1.cs
}
private void btnDeserialize_Click(…) {
FileStream fs = new FileStream(tbInputFileName.Text,
FileMode.Open);
XmlSerializer xs = new
XmlSerializer(typeof(EmployeeType));
emp = (EmployeeType) xs.Deserialize(fs);
fs.Close();
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 83
© 2004 ISS. All rights reserved
xsd.exe
Generates XSD from assembly
public class EmployeeType { <Employee>
public string Name; <Name>Benjamin Gan</Name>
xsd.exe
… Employee.dll …
csc.exe EmployeeType.xsd
} assembly </Employee>
Generates CLR classes from XDR, XML, and XSD
public class EmployeeType {
public string Name;
xsd.exe /classes …
<Employee>
} EmployeeTypeClass.cs
<Name>Benjamin Gan</Name>
…
public class NewDataSet:DataSet {
</Employee> xsd.exe /dataset public class EmployeeDataTable:
DataTabl { … }
Generates a class derived from DataSet that …
} EmployeeTypeDataset.cs
corresponds to the specified schema
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 84
© 2004 ISS. All rights reserved
WebMethod and XmlSerializer
WebMethod parameters are serialized using XmlSerializer
Limited support for complex CLR types
¾ Only public properties are serialized
Does not handle XmlSerializer events
Must use XmlSerializer custom attributes to customize parameters
¾ XmlElement, XmlRoot and XmlType attributes customize XmlSerializer
¾ [XmlElement] controls local <xsd:element> declaration
¾ [XmlRoot] controls global <xsd:element> declaration
¾ [XmlType] controls <xsd:complexType> declaration
WebMethod does not validate Xml data
Use XmlValidatingReader to validate Xml data
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 85
© 2004 ISS. All rights reserved
XmlSerializer Attributes
[XmlType(Namespace="urn:gan-employee-schema")]
[XmlRoot("Employee",
Namespace="urn:gan-employee-schema",
IsNullable=false)] Specifies whether the xsi:null
public class EmployeeType { attribute appears if the class
public string Name; instance is set to a null reference
[XmlElement(DataType="date")]
public DateTime HiredDate;
public string Position;
public int Salary;
public int Bonus;
Serialize/Employee.cs
}
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 86
© 2004 ISS. All rights reserved
Summary
XML is eXtensible Markup Language DOM provides API for programs to
Text base with markups use Xml doc
Name space avoid name clashes SAX provides API to parse Xml doc
Well-formed when correct syntax Xml doc can be embedded in HTML
Valid when correct semantics Use DOM to access XmlNodes
XSLT transforms Xml doc System.Xml namespace
XSD defines types Schema supports XSD
Type defined by DTD, XDR or XSD XPath supports XPathNavigator
Type is based on value space, lexical DOM supports XmlNodes,
space and facets XmlReader, XmlWriter,
Facets define aspects of the value XmlValidatingReader,
space XmlDataDocument
XSD definitions are in simpleTypes Xsl supports Xslt
or complexTypes Serialization supports XmlSerializer
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 87
© 2004 ISS. All rights reserved
References
Essential XML Quick http://www.w3.org/TR/REC-
Reference, Aaron Skonnard and xml
Martin Gudgin, Addison http://www.ietf.org/rfc
Wesley, 2002 http://www.w3.org/TR/2000/R
Scott Seely's book, SOAP: EC-xml-20001006
Cross Platform Web Service http://www.w3.org/DOM/
Development Using XML, http://www.w3.org/XML/Sche
Prentice Hall-PTR, © 2002 ma
Microsoft Press Books http://msdn.microsoft.com/xml/
(http://mspress.microsoft.com/) http://www.xml.com/
XML Step By Step
XML In Action http://www.w3.org/xml/
Developing XML Solutions
O’Reilly Press
XML In A Nutshell
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 88
© 2004 ISS. All rights reserved
Workshop: Contacts
Objective
Develop a web service to manage Contact information
XML
XML
doc
doc
ATA/SE-WSNET/CPM/XML.PPT/V2.0 Web Services using .NET Slide 89
© 2004 ISS. All rights reserved