1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Module 8: Serializing pdf

70 265 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Module 8: Serializing Objects As XML
Trường học Microsoft Corporation
Chuyên ngành XML Serialization
Thể loại module
Năm xuất bản 2002
Thành phố Redmond
Định dạng
Số trang 70
Dung lượng 1,16 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

XML 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 metho

Trang 1

Contents

Overview 1

Lesson: Introduction to XML Serialization 2

Lesson: Serializing Objects Using

Trang 2

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

Trang 3

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)

Trang 4

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

Trang 5

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

Trang 6

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

Trang 7

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

Trang 8

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

Trang 9

What Is XML Serialization?

 Use serialization to persist and to transport objects

 There are two types of serialization:

***************************** 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

Trang 10

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

Trang 11

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

Trang 12

How Is XML Serialization Related to SOAP?

XML 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

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 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

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

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

Trang 13

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

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

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

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

Trang 14

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

Trang 15

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

Trang 16

(continued)

XSD data type NET data type

time DateTime token String unsignedByte Byte

unsignedInt UInt32 unsignedLong UInt64 unsignedShort UInt16

Trang 17

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

}

1 2 3

***************************** 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:

Trang 18

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

Trang 19

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

Trang 20

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

Trang 21

 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

Trang 22

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

Trang 23

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

Trang 24

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:

 IEnumerable objects must have a public Add() method

 ICollection objects must have public Item and Count properties

***************************** 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

Trang 25

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

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

// Set properties and serialize object }

} public class USAddress { public string Street;

public string City;

public string State;

public int Zip;

Trang 26

' 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

The XmlSerializer class can serialize classes that implement the interfaces IEnumerable and ICollection If a class implements the IEnumerable interface, it must also define a public Add() method that takes a single

parameter

A class that implements ICollection in addition to IEnumerable must also

define the following:

 A public Item indexed property of the same type as the type expected by the Add() method

 A public Count property of type integer Serializing arrays and

collections

Trang 27

How to Serialize an Object as XML

 To serialize an object as XML:

1 Create the class definition for the object

2 Create an instance of the object

3 Populate the public fields and properties

4 Construct an appropriate XmlSerializer object

5 Create a container for the serialized objects

6 Call the Serialize() method

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

You can use the XmlSerializer class to serialize an object as XML To do this,

you must create an object, populate its fields and properties, and then call the

Serialize() method of the XmlSerializer class

To serialize an object as XML, you must complete the following steps:

1 Create the class definition for the object

You must define a class with public fields and properties that can be serialized The class must have a default constructor, so if you create a custom constructor, you must also define a constructor that takes no parameters

2 Create an instance of the object

You cannot serialize a class, only an instance of an object, so you must create a new object to be 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

Introduction

Procedure

Trang 28

4 Construct an appropriate XmlSerializer

Depending on your requirements, you must choose the appropriate

constructor to create an instance of the XmlSerializer class In most cases,

you will only need to pass the type of the object to be serialized

The following code shows how to create an XmlSerializer to serialize an instance of an Employee object:

// C#

XmlSerializer MySerializer = new XmlSerializer(typeof(Employee));

' Visual Basic Dim MySerializer As New XmlSerializer(GetType(Employee))

5 Create a container for the serialized objects When you serialize the object, you need to specify where the serialized

XML should be sent You can save the XML to a Stream, TextWriter, or XmlWriter object

The following code shows how to create a new StringWriter object to store the XML The StringWriter class uses an underlying StringBuilder class

to extend the TextWriter class This allows you to treat the XML as a

string

// C#

StringWriter TW = new StringWriter();

' Visual Basic Dim TW As New StringWriter()

6 Call the Serialize() method

When you call the Serialize() method, you must pass the appropriate

parameters depending on the destination of the serialized XML The

Serialize() method has six applicable overloads: two each for Stream, TextWriter, or XmlWriter In each case, you can choose whether to

supply XML namespaces for the serialized object

The following code shows how to call the Serialize() method, specifying a StringWriter object, TW, as the output:

// C#

MySerializer.Serialize(TW, NewEmployee);

' Visual Basic MySerializer.Serialize(TW, NewEmployee)

Trang 29

How to Deserialize an Object from XML

 To deserialize an object from XML:

1 Create an instance of the object

2 Construct an appropriate XmlSerializer object

3 Create a container for the XML document

4 Call the CanDeserialize() method

5 Call the Deserialize() method

6 Cast the returned object to its original type

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

The process of deserializing an object from XML is essentially the reverse of

the process of serializing an object You again must create an XmlSerializer object, but this time you call the Deserialize() method

To deserialize an object from XML, you must complete the following steps:

1 Create an instance of the object

When you deserialize XML, you extract the data from the elements and attributes to populate the fields and properties of an object Therefore, you must have an instance of the object ready to receive the deserialized data

2 Construct an appropriate XmlSerializer

You must create an XmlSerializer object that expects the correct 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))

Introduction

Procedure

Trang 30

3 Create a container for the XML document

The XML document to be deserialized can come from a number of sources,

including a string, file, Stream, or even an XmlDocument object Because the Deserialize() method can only operate on a Stream, TextReader, or XmlReader object, you must first read the XML into one of these objects

The following code assumes that the XML is in a string variable named

XmlData, so the code creates a StringReader object to read from the string:

// C#

StringReader TR = new StringReader(XmlData);

' Visual Basic Dim TR As New StringReader(XmlData)

4 Call the CanDeserialize() method

Depending on the source of the XML to be deserialized, it might not be possible to successfully extract the data and populate the object The

CanDeserialize() method of the XmlSerializer class returns a Boolean

value representing whether the XML can be converted into an object The

CanDeserialize() method only takes an XmlReader object as its input The following code reads a TextReader object into an XmlReader object and then tests the value of the CanDeserialize() method:

// C#

XmlReader XR = new XmlTextReader(TR);

if (MyDeserializer.CanDeserialize(XR)) { // Deserialize XML

} ' Visual Basic Dim XR As New XmlTextReader(TR)

If MyDeserializer.CanDeserialize(XR) ' Deserialize XML

End If

5 Call the Deserialize() method

The Deserialize() method can take a Stream, TextReader, or XmlReader

object as a parameter from which to read XML In each case, the return

value is of type Object However, you cannot implicitly convert an Object

type into the type of the original object; you must convert or cast the object

explicitly

Trang 31

6 Cast the returned object to its original type

To convert one type into another, you can use various methods provided by both Visual Basic and C# These methods apply to different situations In a

situation where you must cast a generic Object type into an explicit object type, Visual Basic provides the DirectCast() and CType() functions, and

C# provides the () operator This is called the cast operator

The following code shows how to deserialize XML from an XmlReader object named XR into a generic object, and then cast it explicitly to an Employee object:

// C#

NewEmp = (Employee)MyDeserializer.Deserialize(XR);

' Visual Basic NewEmp = CType(MyDeserializer.Deserialize(XR), Employee)

Trang 32

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 FOR NON - TRAINER USE ******************************

In this code examination, 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 examine the solution files

1 Open EmployeeData.sln in the folder install_folder\Democode\Mod08\CS

You can also open the Visual Basic version of the solution from the

folder install_folder\Democode\Mod08\VB In this case, substitute the vb

file extension each time the procedure refers to a file with cs file extension

2 In the Visual Studio NET, in the Solution Explorer, double-click the file Employee.cs

3 Examine the structure of the Employee and Money classes

4 Close Employee.cs

5 Double-click the file DataForm.cs

6 Right-click the form and then click View Code

7 Locate the btnSave_Click() method and examine the code that populates the Employee object

The code creates a new Employee object and then sets the value of each

field defined for the object to the data that is typed into the form

8 Locate the SerializeObject() method and examine the code that serializes

Trang 33

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 ******************************

In this lesson, you will learn how to control the serialization and deserialization processes by assigning XML and SOAP attributes to class definitions You will learn about commonly used serialization attributes and how to apply them You should be familiar with the concept and application of XML serialization,

the XmlSerializer class, and how to serialize an object into XML and

deserialize an object from XML

After completing this lesson, you will be able to:

 Define serialization attributes

 List commonly used serialization attributes

 Modify the structure of serialized XML by using attributes

 Serialize SOAP messages

Introduction

Objectives

Trang 34

What Are Serialization Attributes?

 Serialization attributes control how an object is serialized or deserialized

 Serialization attributes are not XML attributes

 Use serialization attributes to:

 Serialize fields and properties as XML attributes

 Change the name of an XML element or attribute

 Change the data type of an XML element or attribute

 Apply a namespace to an XML element or attribute

 Exclude a field or property from serialization

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

When you serialize an object into XML, the class definition for the object determines the structure of the XML document By default, each public field and property is serialized as a child element with the same name as the field or property By using serialization attributes, you have greater control over the structure of the serialized XML

Serialization attributes are objects in the System.Xml.Serialization namespace

that you can apply to class definitions or to public field and property definitions inside a class Their presence typically modifies the default serialization process

You can use serialization attributes to do the following:

 Encode data as an XML attribute rather than as an XML child element

 Change the name used to encode an XML element or attribute

 Change the XSD data type of a serialized XML element or attribute

 Change the namespace associated with an XML element or attribute

 Exclude a field or property from the serialization process

Do not confuse serialization attributes with XML attributes

Trang 35

The following code shows a class definition for an Employee object that

contains serialization attributes These attributes change the serialized XML so that the value of the Email field is stored in an element named <EmailAlias>,

and the value of the StartDate field is stored as an XSD date data type

public string Email;

public int Age;

public Money Salary;

[XmlElement(DataType="date")]

public DateTime StartDate;

} ' Visual Basic Public Class Employee Public Name As String Public Department As String <XmlElement(ElementName:="EmailAlias")> _ Public Email As String

Public Age As Int32 Public Salary As Money <XmlElement(DataType:="date")> _ Public StartDate As DateTime End Class

Example

Ngày đăng: 24/01/2014, 09:20

TỪ KHÓA LIÊN QUAN