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

Tài liệu Module 8: Serializing pdf

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








Contents
Overview 1
Lesson: Introduction to XML Serialization 2
Lesson: Serializing Objects Using
XmlSerializer 16
Lesson: Controlling XML Serialization 27
Review 45
Lab 8.1: Serializing Objects as XML 47
Course Evaluation 63

Module 8: Serializing
Objects as XML




Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or


for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

©2002 Microsoft Corporation. All rights reserved.

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

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



Module 8: Serializing Objects as XML iii

Instructor Notes
This module provides students with the skills needed to create Extensible
Markup Language (XML) documents from the data contained within
programmatic objects. This process is referred to as serialization and can be
used to persist object data or to share object data between applications.
After completing this module, students will be able to:
 Define XML serialization.
 Serialize and deserialize objects by using the XmlSerializer class.
 Control XML serialization by using attributes.


To teach this module, you need the following materials:
 Microsoft® PowerPoint® file 2663A_08.ppt
 Code samples file 2663A_08_code.htm

To prepare for this module:
 Read all of the materials for this module.
 Complete the practices, demonstrations and lab.
 Read the relevant documentation in the Microsoft .NET Framework
Software Development Kit (SDK).

Presentation:
90 minutes

Lab:
60 minutes
Required materials
Preparation tasks
iv Module 8: Serializing Objects as XML


How to Teach This Module
This section contains information that will help you to teach this module.
Lesson: Introduction to XML Serialization
This section describes the instructional methods for teaching each topic in this
lesson.
This topic is very important because it sets up the rest of the module. Ensure
that students are comfortable with the concept of serialization before
continuing. Explain that you can use serialization to create XML data without
using any XmlWriter, XslTransform, or XmlDocument objects.

This topic further explains the concept of serialization by providing specific
examples of when it is used. Invite students to suggest other uses for
serialization. Emphasize that the .NET Framework uses serialization behind the
scenes for interaction with XML Web services.
This topic introduces the Simple Object Access Protocol (SOAP). Students
should be familiar with this protocol, but be prepared to explain the
fundamentals to students who have not worked with XML Web services. Do
not describe XML serialization as an alternative to SOAP. SOAP relies on
XML serialization to encode message data.
XML serialization is a very powerful feature, but some students may be
familiar with the capabilities of binary serialization if they have built enterprise
applications that use a distributed architecture. This topic points out that XML
serialization does not persist the same level of data as binary serialization.
This topic introduces the XML Schema Definition tool (XSD.exe), which you
can use to create XML schemas from many different sources. Emphasize that
this tool is most useful when you map schemas to class files or create schemas
from assemblies. Mapping schemas to class files makes the task of defining
classes whose objects will be serialized later much easier.
This practice should clarify the concepts introduced in the previous topic.
Ensure that students understand why they are performing the tasks prescribed
by the practice and how they can use the tool to simplify the serialization
process.
What Is XML
Serialization?
Why Use XML
Serialization?
How Is XML Serialization
Related to SOAP?
What Are the Limitations
of XML Serialization?

How to Serialize XML
Schemas from Object
Classes
Practice: Generating
Schemas Using XSD.exe
Module 8: Serializing Objects as XML v

Lesson: Serializing Objects Using XmlSerializer
This section describes the instructional methods for teaching each topic in this
lesson.
This demonstration shows an application that uses XML serialization and
deserialization. The functionality exhibited in the demonstration is very similar
to functionality shown in other modules that cover the generation of XML.
Although you will show the code for this application later in this lesson, it is a
good idea to mention that the serialization mechanism automatically generates
the XML and that it is not necessary to use Extensible Stylesheet Language for
Transformation (XSLT) style sheets or the Document Object Model (DOM) to
create the XML displayed.
This topic provides an overview of the XmlSerializer class, including the most
common methods and some of its features. You should not need to spend a lot
of time on this topic, because the remaining topics in this lesson provide full
examples of how to use the class. The information about the IEnumerable and
ICollection interfaces is provided to illustrate the concept that serialization
works with almost any kind of object. However, this is advanced material that
you can cover quickly if it is not of particular interest to the students.
This topic explains the core procedure around which the entire module is built.
Give the topic enough time and emphasis to ensure that all students understand
the serialization mechanism. The procedure itself is very straightforward, so do
not introduce any advanced material here that might obscure the simplicity of
the task.

This topic is essentially the reverse of the previous topic. It should be easy to
teach this topic. The most important point here is that it may not be possible to
deserialize a particular type of object from an XML document. For this reason,
it is recommended that you use the CanDeserialize() method first, rather than
attempt to deserializing the object first.
This code examination walks through the code for the application demonstrated
at the beginning of the lesson. Do not rush through the examination. It is very
important that students see the tasks they have learned applied in the context of
a complete application.
Make sure you are completely familiar with the code before you try to examine
it or you might confuse the students with vague or incorrect information.
Lesson: Controlling XML Serialization
This section describes the instructional methods for teaching each topic in this
lesson.
This topic introduces serialization attributes, which you use to control the
serialization process. Students may have seen different attributes in use in other
applications, so explain that they are used as modifiers for declarations. It is
very easy in this and subsequent topics to confuse serialization attributes, SOAP
serialization attributes, and XML attributes. Emphasize here that the use of the
word “attribute” in this context is an unfortunate naming convention, and that
.NET Framework attributes should not be confused with XML attributes.
When showing the example code, do not discuss the syntax. The next topic
covers the syntax in more detail.
Demonstration:
Serializing and
Deserializin
g

What Is the
XmlSerializer Class?

How to Serialize an
Object as XML
How to Deserialize an
Object from XML
Code Examination:
Serializing and
Deserializing
What Are Serialization
Attributes?
vi Module 8: Serializing Objects as XML


This topic shows the syntax of serialization attributes, and provides other
examples of attributes at work in .NET-based applications. Many students will
recognize the WebMethod and DllImport attributes from other contexts. This
should help them become comfortable with serialization attributes. Do not rush
through this topic. Make sure to spend enough time explaining the syntax for
C# and Microsoft Visual Basic
® as necessary, depending on your audience.
This will save time later when students apply attributes in the practice and lab.
This topic builds on the previous topic to discuss the application of XML
namespaces. Explain that this procedure is usually necessary only when you
apply multiple namespaces with different prefixes.
This topic returns to the concept of SOAP. It discusses the mechanism you use
to encode serialized XML data for inclusion in the payload of a SOAP message.
If students are not familiar with SOAP, take time to explain the protocol, its
purpose, and the structure of a SOAP envelope. Explain that the procedure
discussed here is provided for completeness and that you will usually allow the
.NET Framework to handle communication with XML Web services.
Emphasize again that the .NET Framework uses the serialization classes behind

the scenes.
Review
The review questions are multiple-choice. If there is only one correct answer,
the question states, “Choose the best answer.” If there are multiple correct
answers, the question states, “Choose all that apply.” Where the question
includes code fragments, both C# and Visual Basic versions are provided.
However, the correct answers are different in each case so that you can use both
versions of the question for an audience that contains both C# and Visual Basic
programmers.
Lab 8.1: Serializing Objects as XML
Before beginning the lab, students should complete all of the practices and
answer the Review questions. However, there is no dependency between the
practices and the labs. If students did not successfully complete either of the
practices, the outcome of the lab is not affected.
Each exercise in the lab has starter and solution code in both C# and
Visual Basic.

Lab Setup
There are no lab setup requirements that affect replication or customization.

How to Apply
Serialization Attributes
How to Serialize XML
Namespaces
How to Serialize SOAP
Messages
Module 8: Serializing Objects as XML 1

Overview
 Introduction to XML Serialization

 Serializing Objects Using XmlSerializer
 Controlling XML Serialization

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The Microsoft
® .NET Framework provides a number of classes in the
System.Xml.Serialization namespace that you use to serialize objects as
Extensible Markup Language (XML) and to deserialize XML into objects. In
this module, you will learn about XML serialization, why it is useful, and how
to perform serialization by using the XmlSerializer class.
After completing this module, you will be able to:
 Define XML serialization.
 Serialize and deserialize objects by using the XmlSerializer class.
 Control XML serialization by using attributes.

Introduction
Objectives
2 Module 8: Serializing Objects as XML


Lesson: Introduction to XML Serialization
 What Is XML Serialization?
 Why Use XML Serialization?
 How Is XML Serialization Related to SOAP?
 What Are the Limitations of XML Serialization?
 How to Serialize XML Schemas from Object Classes
 Practice: Generating Schemas Using XSD.exe

*****************************

ILLEGAL FOR NON-TRAINER USE******************************
This lesson introduces XML serialization. You will learn what serialization is
and why it is useful. You will also see how to use XML serialization as an
alternative to the Simple Object Access Protocol (SOAP), and how to use the
XML Schema Definition tool (XSD.exe) to generate XML schemas from a
run-time assembly or to generate classes from an XML schema.
You should be familiar with the following:
 Use of .NET Framework classes to parse and generate XML
 Use of XML schemas to validate the structure and types employed by an
XML document

After completing this lesson, you will be able to:
 Define XML serialization.
 List uses of XML serialization.
 Compare XML serialization to SOAP serialization.
 Describe limitations of XML serialization.
 Generate classes and schemas by using the XML Schema Definition tool.

Introduction
Lesson objectives
Module 8: Serializing Objects as XML 3

What Is XML Serialization?
 Use serialization to persist and to transport objects
 There are two types of serialization:
 Binary
 XML
 XML serialization translates the public properties and
fields of an object into XML
 XML serialization classes allow you to decide the

structure of the XML that is used to persist data
Visual Basic Example C# Example

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
XML is particularly useful for encoding and transporting data so that it can be
read by both computers and human users. Often, the data to be transported
comes from a data source such as a relational database. However, it is possible
that an application might have data and state information stored in
programmatic objects. It is useful to be able to quickly convert the data in those
objects into XML and vice versa. This functionality is provided in the
.NET Framework by the classes in the XML serialization namespace,
System.Xml.Serialization.
Serialization is the conversion of information stored in a programmatic object
into a stream of data, for the purpose of transporting the object’s data.
Serialization in the .NET Framework can take the two forms shown in the
following table.
Type Use

Binary serialization You must use binary serialization to serialize the private
properties, methods, and indexers of an object.
XML serialization You can use XML serialization to translate the public
properties and fields of an object into XML. The XML
generated by this process is World Wide Web Consortium
(W3C) compliant and can be represented by XML Schema
Definition (XSD) schemas.

Introduction
Definition
4 Module 8: Serializing Objects as XML



If your application includes classes that represent a purchase order, you can
send a particular purchase order to a trading partner by serializing the data as
XML in an instance of the PurchaseOrder class and transmitting it by using
Hypertext Transfer Protocol (HTTP). You can strictly control the format of the
XML you create, such as the names of the elements that are used to encode the
data, by using serialization attributes.
The following code defines a class representing a purchase order, and shows the
result of serializing an instance of this class as XML:
// C#
public class PurchaseOrder {
public DateTime PODate;
public Int32 PONumber;
public Double POTotal;
}

' Visual Basic
Public Class PurchaseOrder
Public PODate As DateTime
Public PONumber As Int32
Public POTotal As Double
End Class

<! XML output >
<PurchaseOrder>
<PODate>01/01/2002</PODate>
<PONumber>12345</PONumber>
<POTotal>99.99</POTotal>
</PurchaseOrder>


Similarly, if your application receives an XML document, you can deserialize it
and reconstruct a programmatic object of a given type for use in the application.
Example of XML
serialization
Module 8: Serializing Objects as XML 5

Why Use XML Serialization?
 To exchange object data between applications
 To transport data over the Internet
 To import XML data into an application
 To generate XML that conforms to a predefined schema
 To parse XML that conforms to a predefined schema
 To generate SOAP messages for XML Web services
 To preserve or persist object state

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
XML serialization has many uses related to the persistence and transportation
of data. Because XML is an open, well-defined standard, it is an attractive
choice for serializing data.
You can use the classes provided in the System.Xml.Serialization namespace to
serialize objects as XML, or to deserialize objects from XML. You can use this
functionality to do the following:
 Exchange objects between different applications. For example, you can
transport an object representing an employee from a human-resources
application to an expense-processing application as XML.
 Transport object data over the Internet. For example, you can serialize an
object representing an invoice as XML for transmission from a supplier to a
customer.

 Import XML data into an application when it is converted into an
appropriate object. For example, you can deserialize XML data into a
DataSet object for use in a Microsoft ADO.NET application.
 Convert object classes into an XSD schema by using the XML Schema
Definition tool (XSD.exe). You can generate XML that conforms to a given
schema by serializing an instance of the corresponding class.
 Use XML deserialization to parse XML that conforms to a schema into an
object. You can use XSD.exe to create classes from XML schemas so that
you can convert valid XML documents into object instances.
 Create SOAP-compliant messages for use with XML Web services by
applying SOAP serialization attributes to the class definitions.
 Preserve object state from an application. For example, an application can
persist the state of its objects as serialized XML to a database while
suspended or during maintenance. The application can then deserialize the
XML to recreate the objects when the application resumes normal operation.
Introduction
Uses of XML
serialization
6 Module 8: Serializing Objects as XML


How Is XML Serialization Related to SOAP?
XML serialization
XML serialization
XML serialization
SOAP serialization
SOAP serialization
SOAP serialization
Serializes public fields and properties of
an object into XML

Serializes public fields and properties of
an object into XML
Serializes object method calls into XML
Serializes object method calls into XML
Used to transport objects between
applications and data stores
Used to transport objects between
applications and data stores
Used to transport parameters to an XML
Web service and return results
Used to transport parameters to an XML
Web service and return results
Serialized objects can include linear,
array, and object types
Serialized objects can include linear,
array, and object types
SOAP messages can include linear,
array, and object types
SOAP messages can include linear,
array, and object types
Properties can be serialized as elements
or attributes
Properties can be serialized as elements
or attributes
All SOAP data must be encoded as XML
elements
All SOAP data must be encoded as XML
elements
Serialized XML can use any namespace
Serialized XML can use any namespace

SOAP namespaces must be used for
SOAP elements
SOAP namespaces must be used for
SOAP elements

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can use SOAP to serialize programmatic information as XML. When
communicating with an XML Web service, SOAP encoding converts object
method calls into XML. The .NET Framework uses XML serialization when
creating SOAP messages for XML Web services.
The following points demonstrate the relationship between XML serialization
and SOAP and provide a comparison of the two technologies.
XML serialization SOAP serialization

Serializes public fields and property
values of an object into XML.
Serializes object method calls into XML.

When you serialize an object as XML, you are encoding the data stored in the
public fields and properties of a single object within XML elements and
attributes that represent the structure of the object. SOAP messages contain
information to invoke method calls defined by XML Web services and return
the results of those method calls. You can use XML serialization to encode an
object so that it can be passed as a parameter in a SOAP message.
XML serialization SOAP serialization

Used to transport objects between
applications and data stores.
Used to transport parameters to an XML

Web service and return results.

Introduction
Comparison of XML
serialization and SOAP
Module 8: Serializing Objects as XML 7

When you serialize an object, you can persist or transmit that object as XML to
any data store or application. When you create a SOAP request, you are
encoding parameters in a very specific way so that they can be passed to an
XML Web service. The serialization classes in the .NET Framework can
perform the extra encoding required for SOAP serialization.
XML serialization SOAP serialization

Serialized objects can include linear,
array, and object types.
SOAP messages can include linear, array,
and object types.

XML serialization can serialize any public properties or fields of an object
regardless of data type. This includes simple value types, arrays, objects, and
arrays of objects. This serialization functionality is extended to SOAP
messages, so that SOAP payloads can also encapsulate arrays and object types.
XML serialization SOAP serialization

Properties can be serialized as elements or
attributes.
All data must be encoded as XML
elements.


The .NET Framework serialization classes enable you to encode data by using
XML elements or attributes. However, the SOAP specification allows you to
encode data only by using XML elements. Only metadata can be encoded by
using attributes.
XML serialization SOAP serialization

Serialized XML can use any namespace. SOAP elements must use SOAP
namespaces.

The .NET Framework serialization classes give you complete control over the
namespaces that are used to encode data. If you are manually creating a SOAP
message, you must use the predefined SOAP namespaces for the SOAP
envelope. In addition, the data in the payload must be defined in the namespace
specified by the XML Web service that will accept and process the message.
8 Module 8: Serializing Objects as XML


What Are the Limitations of XML Serialization?
 XML serialization has limitations:
 You can serialize only public properties and fields
 Only the shape of your classes and the data is
contained in the serialized data
 You cannot serialize methods and indexers
 A class must have a default constructor
 Not all XSD data types have associated .NET types
 You can use binary serialization and SOAP serialization
to overcome some of these limitations

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

When serializing an object as XML, you should consider a number of
limitations that can affect the outcome of the serialization.
Many of the following limitations arise because of the way each object is
serialized. You can use binary serialization and SOAP serialization to overcome
some of these limitations.
 You can serialize only public properties and fields. If you need to serialize
non-public data, use the BinaryFormatter class rather than XML
serialization.
 Only the shape of your objects, and the data they contain, is included in the
serialized data. Type identity and assembly information are not included. In
.NET remoting, the type identity of a server-activated object is determined
from a combination of the type and assembly information.
 You cannot serialize methods and indexers. In C#, indexers enable you to
create classes that act like “virtual arrays.” You can access instances of
those classes by using the array access operator ([ ]).
 A class must have a default constructor to be serialized by XmlSerializer.
You can still override the default constructor as necessary.
 Not all XSD data types, such as NMTOKEN and IDREF, have
corresponding types in the .NET Common Type System (CTS). This means
that objects that are deserialized based on type information determined from
a mapped XSD schema can lose some strong typing.

Introduction
Limitations
Module 8: Serializing Objects as XML 9

The following table shows the mapping between XSD data types and .NET data
types.
XSD data type .NET data type


anyURI String
base64Binary Array of Byte objects
boolean Boolean
byte SByte
date DateTime
dateTime DateTime
decimal Decimal
double Double
ENTITY String
ENTITIES String
float Single
gDay String
gMonth String
gMonthDay String
gYear String
gYearMonth String
hexBinary Array of Byte objects
ID String
IDREF String
IDREFS String
int Int32
long Int64
Name String
NCName String
negativeInteger String
NMTOKEN String
NMTOKENS String
normalizedString String
nonNegativeInteger String
nonPositiveInteger String

NOTATION String
positiveInteger String
QName XmlQualifiedName
recurringDate String
duration String
string String
short Int16
10 Module 8: Serializing Objects as XML


(continued)
XSD data type .NET data type

time DateTime
token String
unsignedByte Byte
unsignedInt UInt32
unsignedLong UInt64
unsignedShort UInt16

Module 8: Serializing Objects as XML 11

How to Serialize XML Schemas from Object Classes
 .NET Framework classes are blueprints for objects
 XML schemas are blueprints for XML documents
 XSD.exe is a command-line utility that can convert
between .NET Framework class definitions and XML
schemas
<>
<>

<>
XSD.exe
XSD.exeXSD.exe
XSD.exe
Public class Invoice {
// property and
// field definitions

}
1
1
3
3
2
2

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Microsoft Visual Studio
® .NET includes a useful utility named the XML
Schema Definition tool (XSD.exe) that you can use to generate XSD files based
on different input file formats. You can also use this utility to convert an XML
schema into source code for run-time objects and vice versa.
In general, you use XML serialization to convert objects into XML documents.
In addition, objects are instances of classes, and XML documents are instances
of XML schemas. You can use the command-line utility XSD.exe to convert a
class definition inside a .NET runtime assembly into a corresponding XML
schema. Consequently, you can serialize any object instance you create from
this class into XML that conforms to that schema. You can also use the tool in
the opposite direction, to generate source code for classes from an XML

schema.
In general, you use XSD.exe to infer XML schemas from a number of different
sources, such as XML-Data Reduced (XDR) schemas, XML instances,
dynamic-link libraries (DLLs), and executable .NET Framework assemblies.
XSD.exe also creates class definitions corresponding to a supplied XML
schema.
The syntax for XSD.exe is as follows:
xsd file.ext [/outputdir:directory]

Introduction
Classes and schemas
XML Schema Definition
tool
12 Module 8: Serializing Objects as XML


The outputdir parameter applies for all input file types. The following table
summarizes the operation of the tool.
Input type Operation

XDR When you supply an XDR schema, the tool creates the corresponding
XSD schema. This is possible because XDR is a fully functional
subset of XSD.
XML When you supply an XML instance, the tool infers the corresponding
XSD schema that the instance satisfies.
DLL, EXE When you supply a DLL or EXE run-time assembly, the tool
examines the embedded classes and creates corresponding XSD
schemas for each class. You can use the /type switch to specify the
types to be converted.
XSD When you supply an XSD schema, the tool creates the class

definitions for run-time objects whose structures correspond to those
specified by the schema. You must use either the /classes or /dataset
switches to determine the type of class to be created, and you can also
specify the language in which the classes will be defined.

The following table describes the use of the various switches in more detail.
Option Description

/h[elp] Displays command syntax and options for the tool.
/o[utputdir]:directory Specifies the directory for output files. This argument can
appear only once. The default is the current directory.
/? Displays command syntax and options for the tool.
/c[lasses] Generates classes that correspond to the specified XSD
schema.
/d[ataset] Generates a class derived from the DataSet that
corresponds to the specified XSD schema.
/e[lement]:element Specifies the element in the XSD schema for which to
generate code. By default, all elements are typed. You can
specify this argument more than once.
/l[anguage]:language Specifies the programming language to use for the
generated classes. Choose from CS (default), VB, or JS.
/n[amespace]:namespace Specifies the run-time namespace for the generated types.
The default namespace is Schemas.
/u[ri]:uri Specifies the Uniform Resource Identifier (URI) for the
elements in the schema for which to generate code. If
present, this URI applies to all elements specified by the
/element switch.
/t[ype]:typename Specifies the name of the type for which to create a
schema. You can specify multiple type arguments. If
typename does not specify a namespace, XSD.exe

matches all types in the assembly with the specified type.
If typename specifies a namespace, only that type is
matched. If typename ends with an asterisk character (*),
the tool matches all types that start with the string
preceding the *. If you omit the /type switch, XSD.exe
generates schemas for all types in the assembly.

Module 8: Serializing Objects as XML 13

For example, to convert an XSD schema into C# class files that you can use to
serialize an object into a valid XML instance, use the following:
xsd.exe myschema.xsd /l:CS /c

To convert a .NET Framework assembly that contains a class named
ExpenseReport into an XML schema that you can use to validate serialized
instances of the class, use the following:
xsd.exe ExpenseReport.dll /type:ExpenseReport

Examples of using
XSD.exe
14 Module 8: Serializing Objects as XML


Practice: Generating Schemas Using XSD.exe
 Generate an XSD schema from an instance
document
 Use the schema to generate a class
 Compile the class definitions in the
schema


*****************************
ILLEGAL FOR NON-TRAINER USE******************************
In this practice, you will execute XSD.exe by using a number of different file
formats as input, and then examine the files created.
You will first use an XML document instance to create the corresponding XML
schema. You will then use that schema to generate a C# or Microsoft
Visual Basic
® class definition.
In the second part of the practice, you will compile a class definition into an
assembly and then create a schema based on the class definition inside the
assembly. You will then create the source code for another class definition and
compare it to the original.
 Generate an XSD schema from an XML file
1. Open the file Books.xml in the folder install_folder\Practices\Mod08\XSD.
Examine the structure of the document.
2. Click Start, point to All Programs, point to Microsoft Visual Studio
.NET, point to Visual Studio .NET Tools, and then click Visual Studio
.NET Command Prompt.
Command Prompt window opens, in which you can use the Visual Studio
.NET command-line tools.
3. Type the following command:
cd "\Program Files\Msdntrain\2663\Practices\Mod08\XSD"

4. Type the following command:
xsd.exe Books.xml

A file named Books.xsd is created in the same folder.
5. In Visual Studio .NET, open Books.xsd and examine its structure. Notice
that it corresponds to the structure of the original XML file.


Introduction
Exercise
Module 8: Serializing Objects as XML 15

 Generate a source runtime from an XSD schema
1. At the command prompt, type the following command:
xsd.exe Books.xsd /L:CS /C

A file named Books.cs is created in the same folder.

You can also create a Visual Basic file by using the switch /L:VB
instead of /L:CS.

2. In Visual Studio .NET, open Books.cs or Books.vb and examine the classes.
Notice that the structure of the classes corresponds to the structures in the
original XML file.

 Generate an XSD schema from a .NET runtime assembly
1. In Visual Studio .NET, open the file Employee.cs. Examine the structure of
the classes defined in the file.
2. At the command prompt, type the following command:
csc.exe /target:library Employee.cs

This will compile the C# class file into a .NET DLL.

You can also examine the Employee.vb file and use the command
vbc.exe /target:library Employee.vb to compile the DLL.

3. At the command prompt, type the following command:
xsd.exe Employee.dll


A file named schema0.xsd is created in the same folder.
4. In Visual Studio .NET, open Schema0.xsd and examine its structure. The
structures correspond to the classes in the original C# (or Visual Basic) file.

 Generate a source runtime from an XSD schema
1. At the command prompt, type the following command:
xsd.exe schema0.xsd /L:CS /C

A file named schema0.cs (or schema0.vb) is created in the same folder.

You can also create a Visual Basic file by using the switch /L:VB
instead of /L:CS.

2. In Visual Studio .NET, open schema0.cs and examine the class. Compare
the class to the original class defined in Employee.cs (or Employee.vb).
3. Close Visual Studio .NET.

Note
Note
Note
16 Module 8: Serializing Objects as XML


Lesson: Serializing Objects Using XmlSerializer
 Demonstration: Serializing and Deserializing
 What Is the XmlSerializer Class?
 How to Serialize an Object as XML
 How to Deserialize an Object from XML
 Code Examination: Serializing and Deserializing


*****************************
ILLEGAL FOR NON-TRAINER USE******************************
In this lesson, you will learn about the XmlSerializer class in the
System.Xml.Serialization namespace. You will learn how to use the methods of
this class to serialize objects into XML and deserialize an object from XML.
You should be familiar with the concept of XML serialization and its uses. You
should also be familiar with XSD schemas.
After completing this lesson, you will be able to:
 Describe the XmlSerializer class.
 Serialize an object into XML.
 Deserialize an object from XML.

Introduction
Objectives
Module 8: Serializing Objects as XML 17

Demonstration: Serializing and Deserializing
 A .NET-based application uses the
XmlSerializer class to:
 Serialize an object as XML
 Deserialize an object from XML

*****************************
ILLEGAL FOR NON-TRAINER USE******************************
In this demonstration, you will see how a .NET-based application can serialize
an object as XML and deserialize an object from XML by using the
XmlSerializer class.
 To gather employee data
1. Run EmployeeData.exe.

2. Enter data for an employee. Ensure that an integer is entered for the Age, a
date in the form MM/DD/YYYY is entered for the Start Date, and a decimal
value is entered for the Salary Amount.
3. Click Save.
A message box shows the employee data serialized as XML.
4. Click OK.
A new dialog box shows the employee data deserialized from the XML. The
values stored in the retrieved object are shown in a text box.

Introduction
Demonstration
18 Module 8: Serializing Objects as XML


What Is the XmlSerializer Class?
 The XmlSerializer class is a member of the
System.Xml.Serialization namespace
 The XmlSerializer class provides the following methods for
serializing objects into XML and for deserializing XML into objects:
 Serialize() method
 Deserialize() method
 CanDeserialize() method
 The XmlSerializer class can also serialize objects whose classes
implement IEnumerable or ICollection
 IEnumerable objects must have a public Add() method
 ICollection objects must have public Item and Count properties
Visual Basic Example
C# Example

*****************************

ILLEGAL FOR NON-TRAINER USE******************************
The .NET Framework includes the System.Xml.Serialization namespace, which
contains classes that control serialization and deserialization. The most
important of these is the XmlSerializer class, which provides methods for
performing the actual serialization and deserialization.
The XmlSerializer class is a member of the System.Xml.Serialization
namespace. It provides methods for serializing objects into XML and for
deserializing XML into objects.
The following table lists the methods that you use for serialization.
Method Description

Serialize() Serializes a given object into XML whose structure is defined by
attributes applied to the class definition for the object.
Deserialize() Deserializes an XML document into one or more objects based on
the class definitions for the objects.
CanDeserialize() Determines whether you can deserialize a given XML document
into a particular object.

The XmlSerializer class allows you to serialize the data contained in the public
properties and fields of an object. By default, the value of a property or a field
is encoded as an XML element whose name is the same as that of the property
or field. If a property consists of an array or an object, the values contained in
that array or object are serialized into embedded child elements in the XML.
Introduction
Definition
Methods
Module 8: Serializing Objects as XML 19

To create an instance of the XmlSerializer class, you can use one of the various
constructors that are supplied. The default constructor accepts no parameters

and is not intended to be used in code.
To determine the type of the object that will be serialized, you can use the
GetType() operator provided by Visual Basic, or the typeof() operator
provided by C#, and pass the name of the object class. You can also call the
GetType() method of the object instance itself. Each of these will return the
System.Type object representing the supplied object.
The following table describes common constructors that you can use.
Signature Description

XmlSerializer(Type) Used to serialize an object of the supplied type.
XmlSerializer(XmlTypeMapping) Used to serialize an object into a form that you
can use with SOAP messages by mapping the
fields of the object to SOAP-compliant elements.
XmlSerializer(Type, String) Used to serialize an object with a default XML
namespace specified by the string parameter.
XmlSerializer(Type, Type()) Used to serialize an object with properties of type
Object. The Type() parameter is a Type array
that contains the types that should be serialized.
XmlSerializer(Type,
XmlRootAttribute)
Used to serialize an object whose root element is
specified by the supplied XmlRootAttribute
object parameter.

The following example shows how to create an XmlSerializer object that you
use to serialize an object of type USAddress:
// C#
using System.Xml.Serialization;

public class MySerializer {

public static void Main() {
XmlSerializer serializer =
new XmlSerializer(typeof(USAddress));
// Set properties and serialize object
}
}

public class USAddress {
public string Street;
public string City;
public string State;
public int Zip;
}

Code continued on the following page.
Creating an
XmlSerialize
r

Constructors
Example

×