Thông tin tài liệu
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
[...]... defined in Employee.cs (or Employee.vb) 3 Close Visual Studio NET 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... 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... on the following page 20 Module 8: Serializing Objects as XML ' Visual Basic Imports System.Xml.Serialization Module MySerializer Sub Main() Dim serializer As New XmlSerializer(GetType(USAddress)) ' Set properties and serialize object End Sub End Module Public Class USAddress Public Street as String Public City as String Public State as String Public Zip as Int32 End Class Serializing arrays and collections... the XML The values stored in the retrieved object are shown in a text box 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()... schemas Objectives After completing this lesson, you will be able to: Describe the XmlSerializer class Serialize an object into XML Deserialize an object from XML 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... serialized 3 Populate the public fields and properties Because serializing an object means serializing the data contained in the object, you must assign values to the public fields and properties of the object If the object has private fields or indexers, you can also assign values to them, but those values will not be serialized 22 Module 8: Serializing Objects as XML 4 Construct an appropriate XmlSerializer... explicitly to an Employee object: // C# NewEmp = (Employee)MyDeserializer.Deserialize(XR); ' Visual Basic NewEmp = CType(MyDeserializer.Deserialize(XR), Employee) 26 Module 8: Serializing Objects as XML Code Examination: Serializing and Deserializing A NET-based application uses the XmlSerializer class to: Serialize an object as XML Deserialize an object from XML *****************************ILLEGAL... object type, similar to the procedure for serializing an object For example, the following code creates an XmlSerializer object named MyDeserializer that expects to deserialize XML into an Employee object: // C# XmlSerializer MyDeserializer = new XmlSerializer(typeof(Employee)); ' Visual Basic Dim MyDeserializer As New XmlSerializer(GetType(Employee)) 24 Module 8: Serializing Objects as XML 3 Create a... code that deserializes an object from XML 10 Close DataForm.cs and close Visual Studio NET Module 8: Serializing Objects as XML 27 Lesson: Controlling XML Serialization What Are Serialization Attributes? How to Apply Serialization Attributes How to Serialize XML Namespaces How to Serialize SOAP Messages Practice: Serializing SOAP Messages *****************************ILLEGAL FOR NON-TRAINER USE******************************... 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 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 . 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. .
Object from XML
Code Examination:
Serializing and
Deserializing
What Are Serialization
Attributes?
vi Module 8: Serializing Objects as XML
This
Ngày đăng: 24/01/2014, 09:20
Xem thêm: Tài liệu Module 8: Serializing pdf