Академический Документы
Профессиональный Документы
Культура Документы
Serialization
Serialization How-to Topics
Binary Serialization
Serialization Concepts
Basic Serialization
Selective Serialization
Custom Serialization
Steps in the Serialization Process
Version Tolerant Serialization
Serialization Guidelines
How to: Chunk Serialized Data
XML and SOAP Serialization
How to: Control Serialization of Derived Classes
Introducing XML Serialization
How to: Deserialize an Object
Examples of XML Serialization
The XML Schema Definition Tool and XML Serialization
How to: Use the XML Schema Definition Tool to Generate Classes and XML Schema
Documents
Controlling XML Serialization Using Attributes
Attributes That Control XML Serialization
How to: Specify an Alternate Element Name for an XML Stream
How to: Serialize an Object
How to: Qualify XML Element and XML Attribute Names
XML Serialization with XML Web Services
How to: Serialize an Object as a SOAP-Encoded XML Stream
How to: Override Encoded SOAP XML Serialization
Attributes That Control Encoded SOAP Serialization
<system.xml.serialization> Element
<dateTimeSerialization> Element
<schemaImporterExtensions> Element
<add> Element for <xmlSchemaImporterExtensions>
<xmlSerializer> Element
Serialization Tools
XML Serializer Generator Tool (Sgen.exe)
XML Schema Definition Tool (Xsd.exe)
Serialization Samples
Basic Serialization Technology Sample
Custom Serialization Order With XmlSerializer
SchemaImporterExtension Technology Sample
Version Tolerant Serialization Technology Sample
Web Services Generics Serialization Technology Sample
Web Services IXmlSerializable Technology Sample
Serialization in the .NET Framework
4/14/2017 • 1 min to read • Edit Online
Serialization is the process of converting the state of an object into a form that can be persisted or transported. The
complement of serialization is deserialization, which converts a stream into an object. Together, these processes
allow data to be easily stored and transferred.
The .NET Framework features two serializing technologies:
Binary serialization preserves type fidelity, which is useful for preserving the state of an object between
different invocations of an application. For example, you can share an object between different applications
by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the
network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or
application domain to another.
XML serialization serializes only public properties and fields and does not preserve type fidelity. This is
useful when you want to provide or consume data without restricting the application that uses the data.
Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise
an open standard, which makes it an attractive choice.
In This Section
Serialization How-to Topics
Lists links to How-to topics contained in this section.
Binary Serialization
Describes the binary serialization mechanism that is included with the common language runtime.
XML and SOAP Serialization
Describes the XML and SOAP serialization mechanism that is included with the common language runtime.
Serialization Tools
These tools help develop serialization code.
Serialization Samples
The samples demonstrate how to do serialization.
Reference
System.Runtime.Serialization
Contains classes that can be used for serializing and deserializing objects.
System.Xml.Serialization
Contains classes that can be used to serialize objects into XML format documents or streams.
Related Sections
Serialization How-to Topics
4/14/2017 • 1 min to read • Edit Online
The following list includes links to the How-to topics found in the conceptual documentation for serialization.
How to: Serialize an Object
How to: Deserialize an Object
How to: Use the XML Schema Definition Tool to Generate Classes and XML Schema Documents
How to: Specify an Alternate Element Name for an XML Stream
How to: Control Serialization of Derived Classes
How to: Qualify XML Element and XML Attribute Names
How to: Serialize an Object as a SOAP-Encoded XML Stream
How to: Override Encoded SOAP XML Serialization
How to: Chunk Serialized Data
See Also
Serialization
Binary Serialization
4/14/2017 • 2 min to read • Edit Online
Serialization can be defined as the process of storing the state of an object to a storage medium. During this
process, the public and private fields of the object and the name of the class, including the assembly containing
the class, are converted to a stream of bytes, which is then written to a data stream. When the object is
subsequently deserialized, an exact clone of the original object is created.
When implementing a serialization mechanism in an object-oriented environment, you have to make a number of
tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are
given sufficient control over the process. For example, situations may arise where simple binary serialization is
not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized. The
following sections examine the robust serialization mechanism provided with the .NET Framework and highlight a
number of important features that allow you to customize the process to meet your needs.
NOTE
The state of a UTF-8 or UTF-7 encoded object is not preserved if the object is serialized and deserialized using different .NET
Framework versions.
In This Section
Serialization Concepts
Discusses two scenarios where serialization is useful: when persisting data to storage and when passing objects
across application domains.
Basic Serialization
Describes how to use the binary and SOAP formatters to serialize objects.
Selective Serialization
Describes how to prevent some members of a class from being serialized.
Custom Serialization
Describes how to customize serialization for a class by using the ISerializable interface.
Steps in the Serialization Process
Describes the course of action serialization takes when the Serialize method is called on a formatter.
Version Tolerant Serialization
Explains how to create serializable types that can be modified over time without causing applications to throw
exceptions.
Serialization Guidelines
Provides some general guidelines for deciding when to serialize an object.
Reference
System.Runtime.Serialization
Contains classes that can be used for serializing and deserializing objects.
Related Sections
XML and SOAP Serialization
Describes the XML serialization mechanism that is included with the common language runtime.
Security and Serialization
Describes the secure coding guidelines to follow when writing code that performs serialization.
Remote Objects
Describes the various communications methods available in the .NET Framework for remote communications.
XML Web Services Created Using ASP.NET and XML Web Service Clients
Provides topics that describe and explain how to program XML Web services created using ASP.NET.
Serialization Concepts
4/14/2017 • 1 min to read • Edit Online
Why would you want to use serialization? The two most important reasons are to persist the state of an object to a
storage medium so an exact copy can be re-created at a later stage, and to send the object by value from one
application domain to another. For example, serialization is used to save session state in ASP.NET and to copy
objects to the Clipboard in Windows Forms. It is also used by remoting to pass objects by value from one
application domain to another.
In This Section
Persistent Storage
Describes the need for serializing an object.
Marshal by Value
Describes the marshal-by-value process.
Related Sections
Binary Serialization
Describes the binary serialization mechanism that is included with the common language runtime.
Remote Objects
Describes the various communications methods available in the .NET Framework for remote communications.
XML and SOAP Serialization
Describes the XML and SOAP serialization mechanism that is included with the common language runtime.
Persistent Storage
4/14/2017 • 1 min to read • Edit Online
It is often necessary to store the value of the fields of an object to disk and then, later, retrieve this data. Although
this is easy to achieve without relying on serialization, this approach is often cumbersome and error prone, and
becomes progressively more complex when you need to track a hierarchy of objects. Imagine writing a large
business application, that contains thousands of objects, and having to write code to save and restore the fields and
properties to and from disk for each object. Serialization provides a convenient mechanism for achieving this
objective.
The common language runtime manages how objects are stored in memory and provides an automated
serialization mechanism by using reflection. When an object is serialized, the name of the class, the assembly, and
all the data members of the class instance are written to storage. Objects often store references to other instances
in member variables. When the class is serialized, the serialization engine tracks referenced objects, already
serialized, to ensure that the same object is not serialized more than once. The serialization architecture provided
with the .NET Framework correctly handles object graphs and circular references automatically. The only
requirement placed on object graphs is that all objects, referenced by the serialized object, must also be marked as
Serializable (for more information, see Basic Serialization). If this is not done, an exception will be thrown when
the serializer attempts to serialize the unmarked object.
When the serialized class is deserialized, the class is recreated and the values of all the data members are
automatically restored.
See Also
Serialization Concepts
XML and SOAP Serialization
Marshal by Value
4/14/2017 • 1 min to read • Edit Online
Objects are valid only in the application domain where they are created. Any attempt to pass the object as a
parameter or return it as a result will fail unless the object derives from MarshalByRefObject or is marked as
Serializable . If the object is marked as Serializable , the object will automatically be serialized, transported from
the one application domain to the other, and then deserialized to produce an exact copy of the object in the second
application domain. This process is typically referred to as marshal-by-value.
When an object derives from MarshalByRefObject , an object reference is passed from one application domain to
another, rather than the object itself. You can also mark an object that derives from MarshalByRefObject as
Serializable . When this object is used with remoting, the formatter responsible for serialization, which has been
preconfigured with a surrogate selector ( SurrogateSelector ), takes control of the serialization process, and replaces
all objects derived from MarshalByRefObject with a proxy. Without the SurrogateSelector in place, the serialization
architecture follows the standard serialization rules described in Steps in the Serialization Process.
See Also
Serialization Concepts
XML and SOAP Serialization
Basic Serialization
6/2/2017 • 2 min to read • Edit Online
The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows.
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
The code example below shows how an instance of this class can be serialized to a file.
This example uses a binary formatter to do the serialization. All you need to do is create an instance of the stream
and the formatter you intend to use, and then call the Serialize method on the formatter. The stream and the
object to serialize are provided as parameters to this call. Although it is not explicitly demonstrated in this example,
all member variables of a class will be serialized—even variables marked as private. In this aspect, binary
serialization differs from the XMLSerializer Class, which only serializes public fields. For information on excluding
member variables from binary serialization, see Selective Serialization.
Restoring the object back to its former state is just as easy. First, create a stream for reading and a Formatter, and
then instruct the formatter to deserialize the object. The code example below shows how this is done.
The BinaryFormatter used above is very efficient and produces a compact byte stream. All objects serialized with
this formatter can also be deserialized with it, which makes it an ideal tool for serializing objects that will be
deserialized on the .NET Framework. It is important to note that constructors are not called when an object is
deserialized. This constraint is placed on deserialization for performance reasons. However, this violates some of
the usual contracts the runtime makes with the object writer, and developers should ensure that they understand
the ramifications when marking an object as serializable.
If portability is a requirement, use the SoapFormatter instead. Simply replace the BinaryFormatter in the code
above with SoapFormatter, and call Serialize and Deserialize as before. This formatter produces the following
output for the example used above.
<SOAP-ENV:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP- ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle=
"http://schemas.microsoft.com/soap/encoding/clr/1.0"
"http://schemas.xmlsoap.org/soap/encoding/"
xmlns:a1="http://schemas.microsoft.com/clr/assem/ToFile">
<SOAP-ENV:Body>
<a1:MyObject id="ref-1">
<n1>1</n1>
<n2>24</n2>
<str id="ref-3">Some String</str>
</a1:MyObject>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
It is important to note that the Serializable attribute cannot be inherited. If you derive a new class from MyObject ,
the new class must be marked with the attribute as well, or it cannot be serialized. For example, when you attempt
to serialize an instance of the class below, you will get a SerializationException informing you that the MyStuff
type is not marked as serializable.
Using the Serializable attribute is convenient, but it has limitations as demonstrated above. Refer to the
Serialization Guidelines for information about when you should mark a class for serialization; serialization cannot
be added to a class after it has been compiled.
See Also
Binary Serialization
XML and SOAP Serialization
Selective Serialization
4/14/2017 • 1 min to read • Edit Online
A class often contains fields that should not be serialized. For example, assume a class stores a thread ID in a
member variable. When the class is deserialized, the thread stored the ID for when the class was serialized might
no longer be running; so serializing this value does not make sense. You can prevent member variables from being
serialized by marking them with the NonSerialized attribute as follows.
[Serializable]
public class MyObject
{
public int n1;
[NonSerialized] public int n2;
public String str;
}
If possible, make an object that could contain security-sensitive data nonserializable. If the object must be
serialized, apply the NonSerialized attribute to specific fields that store sensitive data. If you do not exclude these
fields from serialization, be aware that the data they store will be exposed to any code that has permission to
serialize. For more information about writing secure serialization code, see Security and Serialization.
See Also
Binary Serialization
XML and SOAP Serialization
Security and Serialization
Custom Serialization
5/19/2017 • 7 min to read • Edit Online
Custom serialization is the process of controlling the serialization and deserialization of a type. By controlling
serialization, it is possible to ensure serialization compatibility, which is the ability to serialize and deserialize
between versions of a type without breaking the core functionality of the type. For example, in the first version of a
type, there may be only two fields. In the next version of a type, several more fields are added. Yet the second
version of an application must be able to serialize and deserialize both types. The following sections describe how
to control serialization.
IMPORTANT
In versions previous to.NET Framework 4.0, serialization of custom user data in a partially trusted assembly was accomplished
using the GetObjectData. Starting with version 4.0, that method is marked with the SecurityCriticalAttribute attribute which
prevents execution in partially trusted assemblies. To work around this condition, implement the ISafeSerializationData
interface.
[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;
public MyObject()
{
}
<Serializable()> _
Public Class MyObject
Implements ISerializable
Public n1 As Integer
Public n2 As Integer
Public str As String
When GetObjectData is called during serialization, you are responsible for populating the SerializationInfo
provided with the method call. Add the variables to be serialized as name and value pairs. Any text can be used as
the name. You have the freedom to decide which member variables are added to the SerializationInfo, provided
that sufficient data is serialized to restore the object during deserialization. Derived classes should call the
GetObjectData method on the base object if the latter implements ISerializable.
Note that serialization can allow other code to see or modify object instance data that is otherwise inaccessible.
Therefore, code that performs serialization requires the SecurityPermission with the SerializationFormatter flag
specified. Under default policy, this permission is not given to Internet-downloaded or intranet code; only code on
the local computer is granted this permission. The GetObjectData method must be explicitly protected either by
demanding the SecurityPermissionwith theSerializationFormatter flag specified or by demanding other
permissions that specifically help protect private data.
If a private field stores sensitive information, you should demand the appropriate permissions on GetObjectData
to protect the data. Remember that code that has been granted SecurityPermissionwith
theSerializationFormatter flag specified can view and modify the data stored in private fields. A malicious caller
granted this SecurityPermission can view data such as hidden directory locations or granted permissions and use
the data to exploit a security vulnerability on the computer. For a complete list of the security permission flags you
can specify, see the SecurityPermissionFlag Enumeration .
It is important to stress that when ISerializable is added to a class you must implement both GetObjectData and
the special constructor. The compiler warns you if GetObjectData is missing. However, because it is impossible to
enforce the implementation of a constructor, no warning is provided if the constructor is absent, and an exception
is thrown when an attempt is made to deserialize a class without the constructor.
The current design was favored above a SetObjectData method to get around potential security and versioning
problems. For example, a SetObjectData method must be public if it is defined as part of an interface; thus users
must write code to defend against having the SetObjectData method called multiple times. Otherwise, a malicious
application that calls the SetObjectData method on an object in the process of executing an operation can cause
potential problems.
During deserialization, SerializationInfo is passed to the class using the constructor provided for this purpose.
Any visibility constraints placed on the constructor are ignored when the object is deserialized; so you can mark the
class as public, protected, internal, or private. However, it is a best practice to make the constructor protected
unless the class is sealed, in which case the constructor should be marked private. The constructor should also
perform thorough input validation. To avoid misuse by malicious code, the constructor should enforce the same
security checks and permissions required to obtain an instance of the class using any other constructor. If you do
not follow this recommendation, malicious code can preserialize an object, obtain control with the
SecurityPermissionwith theSerializationFormatter flag specified and deserialize the object on a client computer
bypassing any security that would have been applied during standard instance construction using a public
constructor.
To restore the state of the object, simply retrieve the values of the variables from SerializationInfo using the
names used during serialization. If the base class implements ISerializable, the base constructor should be called
to allow the base object to restore its variables.
When you derive a new class from one that implements ISerializable, the derived class must implement both the
constructor as well as the GetObjectData method if it has variables that need to be serialized. The following code
example shows how this is done using the MyObject class shown previously.
[Serializable]
public class ObjectTwo : MyObject
{
public int num;
<Serializable()> _
Public Class ObjectTwo
Inherits MyObject
Public num As Integer
End Sub
<SecurityPermissionAttribute(SecurityAction.Demand, _
SerializationFormatter := True)> _
Public Overrides Sub GetObjectData(ByVal si As _
SerializationInfo, ByVal context As StreamingContext)
MyBase.GetObjectData(si, context)
si.AddValue("num", num)
End Sub
End Class
Do not forget to call the base class in the deserialization constructor. If this is not done, the constructor on the base
class is never called, and the object is not fully constructed after deserialization.
Objects are reconstructed from the inside out; and calling methods during deserialization can have undesirable
side effects, because the methods called might refer to object references that have not been deserialized by the
time the call is made. If the class being deserialized implements the IDeserializationCallback , the
OnDeserialization` method is automatically called when the entire object graph has been deserialized. At this point,
all the child objects referenced have been fully restored. A hash table is a typical example of a class that is difficult
to deserialize without using the event listener. It is easy to retrieve the key and value pairs during deserialization,
but adding these objects back to the hash table can cause problems, because there is no guarantee that classes that
derived from the hash table have been deserialized. Calling methods on a hash table at this stage is therefore not
advisable.
See Also
Binary Serialization
XML and SOAP Serialization
Security and Serialization
Steps in the Serialization Process
4/14/2017 • 1 min to read • Edit Online
When the Serialize method is called on a formatter] , object serialization proceeds according to the following
sequence of rules:
A check is made to determine whether the formatter has a surrogate selector. If the formatter does, check
whether the surrogate selector handles objects of the given type. If the selector handles the object type,
ISerializable.GetObjectData is called on the surrogate selector.
If there is no surrogate selector or if it does not handle the object type, a check is made to determine
whether the object is marked with the Serializable attribute. If the object is not, a SerializationException
is thrown.
If the object is marked appropriately, check whether the object implements the ISerializabl interface. If
the object does, GetObjectData is called on the object.
If the object does not implement ISerializable , the default serialization policy is used, serializing all fields
not marked as NonSerialized .
See Also
Binary Serialization
XML and SOAP Serialization
Version Tolerant Serialization
5/23/2017 • 6 min to read • Edit Online
In version 1.0 and 1.1 of the .NET Framework, creating serializable types that would be reusable from one version
of an application to the next was problematic. If a type was modified by adding extra fields, the following problems
would occur:
Older versions of an application would throw exceptions when asked to deserialize new versions of the old
type.
Newer versions of an application would throw exceptions when deserializing older versions of a type with
missing data.
Version Tolerant Serialization (VTS) is a set of features introduced in .NET Framework 2.0 that makes it easier, over
time, to modify serializable types. Specifically, the VTS features are enabled for classes to which the
SerializableAttribute attribute has been applied, including generic types. VTS makes it possible to add new fields to
those classes without breaking compatibility with other versions of the type. For a working sample application, see
Version Tolerant Serialization Technology Sample.
The VTS features are enabled when using the BinaryFormatter. Additionally, all features except extraneous data
tolerance are also enabled when using the SoapFormatter. For more information about using these classes for
serialization, see Binary Serialization.
Feature List
The set of features includes the following:
Tolerance of extraneous or unexpected data. This enables newer versions of the type to send data to older
versions.
Tolerance of missing optional data. This enables older versions to send data to newer versions.
Serialization callbacks. This enables intelligent default value setting in cases where data is missing.
In addition, there is a feature for declaring when a new optional field has been added. This is the VersionAdded
property of the OptionalFieldAttribute attribute.
These features are discussed in greater detail below.
[Serializable]
public class Address
{
public string Street;
public string City;
[OptionalField]
public string CountryField;
}
<Serializable> _
Public Class Address
Public Street As String
Public City As String
<OptionalField> _
Public CountryField As String
End Class
Serialization Callbacks
Serialization callbacks are a mechanism that provides hooks into the serialization/deserialization process at four
points.
[OnDeserializing]
private void SetCountryRegionDefault(StreamingContext sc)
{
CountryField = "Japan";
}
<OnDeserializing>
Private Sub SetCountryRegionDefault(StreamingContext sc)
CountryField = "Japan";
End Sub
The intended use of these methods is for versioning. During deserialization, an optional field may not be correctly
initialized if the data for the field is missing. This can be corrected by creating the method that assigns the correct
value, then applying either the OnDeserializingAttribute or OnDeserializedAttribute attribute to the method.
The following example shows the method in the context of a type. If an earlier version of an application sends an
instance of the Address class to a later version of the application, the CountryField field data will be missing. But
after deserialization, the field will be set to a default value "Japan."
[Serializable]
public class Address
{
public string Street;
public string City;
[OptionalField]
public string CountryField;
[OnDeserializing]
private void SetCountryRegionDefault (StreamingContext sc)
{
CountryField = "Japan";
}
}
<Serializable> _
Public Class Address
Public Street As String
Public City As String
<OptionalField> _
Public CountryField As String
<OnDeserializing> _
Private Sub SetCountryRegionDefault(StreamingContext sc)
CountryField = "Japan";
End Sub
End Class
// Version 2.0
[Serializable]
public class Person
{
public string FullName;
[OptionalField(VersionAdded = 2)]
public string NickName;
[OptionalField(VersionAdded = 2)]
public DateTime BirthDate;
}
// Version 3.0
[Serializable]
public class Person
{
public string FullName;
[OptionalField(VersionAdded=2)]
public string NickName;
[OptionalField(VersionAdded=2)]
public DateTime BirthDate;
[OptionalField(VersionAdded=3)]
public int Weight;
}
<OptionalField(VersionAdded := 2)> _
Public NickName As String
<OptionalField(VersionAdded := 2)> _
Public BirthDate As DateTime
End Class
<OptionalField(VersionAdded := 2)> _
Public NickName As String
<OptionalField(VersionAdded := 2)> _
Public BirthDate As DateTime
<OptionalField(VersionAdded := 3)> _
Public Weight As Integer
End Class
SerializationBinder
Some users may need to control which class to serialize and deserialize because a different version of the class is
required on the server and client. SerializationBinder is an abstract class used to control the actual types used
during serialization and deserialization. To use this class, derive a class from SerializationBinder and override the
BindToName System.String, System.String)?qualifyHint=False&autoUpgrade=True and BindToType
System.String)?qualifyHint=False&autoUpgrade=True methods. For more information, seeControlling
Serialization and Deserialization with SerializationBinder.
Best Practices
To ensure proper versioning behavior, follow these rules when modifying a type from version to version:
Never remove a serialized field.
Never apply the NonSerializedAttribute attribute to a field if the attribute was not applied to the field in the
previous version.
Never change the name or the type of a serialized field.
When adding a new serialized field, apply the OptionalFieldAttribute attribute.
When removing a NonSerializedAttribute attribute from a field (that was not serializable in a previous
version), apply the OptionalFieldAttribute attribute.
For all optional fields, set meaningful defaults using the serialization callbacks unless 0 or null as defaults
are acceptable.
To ensure that a type will be compatible with future serialization engines, follow these guidelines:
Always set the VersionAdded property on the OptionalFieldAttribute attribute correctly.
Avoid branched versioning.
See Also
SerializableAttribute
BinaryFormatter
SoapFormatter
VersionAdded
OptionalFieldAttribute
OnDeserializingAttribute
OnDeserializedAttribute
OnDeserializingAttribute
OnSerializedAttribute
StreamingContext
NonSerializedAttribute
Binary Serialization
Serialization Guidelines
4/14/2017 • 11 min to read • Edit Online
This document lists the guidelines to consider when designing an API to be serialized.
The .NET Framework offers three main serialization technologies that are optimized for various serialization
scenarios. The following table lists these technologies and the main Framework types related to these technologies.
DataContractSerializer JSON
NetDataContractSerializer
DataContractJsonSerializer
ISerializable
BinaryFormatter
SoapFormatter
When you design new types, you should decide which, if any, of these technologies those types need to support.
The following guidelines describe how to make that choice and how to provide such support. These guidelines are
not meant to help you choose which serialization technology you should use in the implementation of your
application or library. Such guidelines are not directly related to API design and thus are not within the scope of
this topic.
Guidelines
DO think about serialization when you design new types.
Serialization is an important design consideration for any type, because programs might need to persist or
transmit instances of the type.
Choosing the Right Serialization Technology to Support
Any given type can support none, one, or more of the serialization technologies.
CONSIDER supporting data contract serialization if instances of your type might need to be persisted or
used in Web Services.
CONSIDER supporting the XML serialization instead of or in addition to data contract serialization if you
need more control over the XML format that is produced when the type is serialized.
This may be necessary in some interoperability scenarios where you need to use an XML construct that is
not supported by data contract serialization, for example, to produce XML attributes.
CONSIDER supporting runtime serialization if instances of your type need to travel across .NET Remoting
boundaries.
AVOID supporting runtime serialization or XML serialization just for general persistence reasons. Prefer data
contract serialization instead
Supporting Data Contract Serialization
Types can support data contract serialization by applying the DataContractAttribute to the type and the
DataMemberAttribute to the members (fields and properties) of the type.
[DataContract]
class Person
{
[DataMember]
string LastName { get; set; }
[DataMember]
string FirstName { get; set; }
End Class
1. CONSIDER marking data members of your type public if the type can be used in partial trust. In full trust,
data contract serializers can serialize and deserialize nonpublic types and members, but only public
members can be serialized and deserialized in partial trust.
2. DO implement a getter and setter on all properties that have Data-MemberAttribute. Data contract
serializers require both the getter and the setter for the type to be considered serializable. If the type won’t
be used in partial trust, one or both of the property accessors can be nonpublic.
[DataContract]
class Person2
{
string lastName;
string firstName;
[DataMember]
public string LastName
{
// Implement get and set.
get { return lastName; }
private set { lastName = value; }
[DataMember]
public string FirstName
{
// Implement get and set.
get { return firstName; }
private set { firstName = value; }
}
}
End Property
End Get
Set(ByVal value As String)
firstNameValue = value
End Set
End Property
End Class
[DataContract]
class Person3
{
[DataMember]
string lastName;
[DataMember]
string firstName;
string fullName;
<DataContract()> _
Class Person3
<DataMember()> Private lastNameValue As String
<DataMember()> Private firstNameValue As String
Dim fullNameValue As String
The OnDeserializedAttribute attribute is the most commonly used callback attribute. The other attributes in
the family are OnDeserializingAttribute,
OnSerializingAttribute, and OnSerializedAttribute. They can be used to mark callbacks that get executed
before deserialization, before serialization, and finally, after serialization, respectively.
4. CONSIDER using the KnownTypeAttribute to indicate concrete types that should be used when deserializing
a complex object graph.
For example, if a type of a deserialized data member is represented by an abstract class, the serializer will
need the known type information to decide what concrete type to instantiate and assign to the member. If
the known type is not specified using the attribute, it will need to be passed to the serializer explicitly (you
can do it by passing known types to the serializer constructor) or it will need to be specified in the
configuration file.
[DataMember]
string fullNameValue;
[DataMember]
Address address; // Address is abstract
[DataContract]
public abstract class Address
{
public abstract string FullAddress { get; }
}
[DataContract]
public class USAddress : Address
{
[DataMember]
public string Street { get; set; }
[DataMember]
public string City { get; set; }
[DataMember]
public string State { get; set; }
[DataMember]
public string ZipCode { get; set; }
End Property
End Class
In cases where the list of known types is not known statically (when the Person class is compiled), the
KnownTypeAttribute can also point to a method that returns a list of known types at runtime.
5. DO consider backward and forward compatibility when creating or changing serializable types.
Keep in mind that serialized streams of future versions of your type can be deserialized into the current
version of the type, and vice versa. Make sure you understand that data members, even private and internal,
cannot change their names, types, or even their order in future versions of the type unless special care is
taken to preserve the contract using explicit parameters to the data contract attributes.Test compatibility of
serialization when making changes to serializable types. Try deserializing the new version into an old
version, and vice versa.
6. CONSIDER implementing IExtensibleDataObject interface to allow round-tripping between different
versions of the type.
The interface allows the serializer to ensure that no data is lost during round-tripping. The ExtensionData
property stores any data from the future version of the type that is unknown to the current version. When
the current version is subsequently serialized and deserialized into a future version, the additional data will
be available in the serialized stream through the ExtensionData property value.
// Implement the IExtensibleDataObject interface.
[DataContract]
class Person5 : IExtensibleDataObject
{
ExtensionDataObject serializationData;
[DataMember]
string fullNameValue;
ExtensionDataObject IExtensibleDataObject.ExtensionData
{
get
{
return serializationData;
}
set { serializationData = value; }
}
}
2. CONSIDER implementing the IXmlSerializable interface if you want even more control over the shape of the
serialized XML than what’s offered by applying the XML Serialization attributes. Two methods of the
interface, ReadXmland WriteXml, allow you to fully control the serialized XML stream. You can also control
the XML schema that gets generated for the type by applying the XmlSchemaProviderAttribute attribute.
Supporting Runtime Serialization
Runtime serialization is a technology used by .NET Remoting. If you think your types will be transported using .NET
Remoting, you need to make sure they support runtime serialization.
The basic support for runtime serialization can be provided by applying the SerializableAttribute attribute, and
more advanced scenarios involve implementing a simple runtime serializable pattern (implement -ISerializable
and provide a serialization constructor).
1. CONSIDER supporting runtime serialization if your types will be used with .NET Remoting. For example, the
System.AddIn namespace uses .NET Remoting, and so all types exchanged between System.AddIn add-ins
need to support runtime serialization.
<Serializable()> Public Class Person6 ' Support runtime serialization with the SerializableAttribute.
2. CONSIDER implementing the runtime serializable pattern if you want complete control over the
serialization process. For example, if you want to transform data as it gets serialized or deserialized.
The pattern is very simple. All you need to do is implement the ISerializable interface and provide a special
constructor that is used when the object is deserialized.
public Person_Runtime_Serializable() { }
protected Person_Runtime_Serializable(SerializationInfo info, StreamingContext context){
if (info == null) throw new System.ArgumentNullException("info");
fullName = (string)info.GetValue("name", typeof(string));
}
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context) {
if (info == null) throw new System.ArgumentNullException("info");
info.AddValue("name", fullName);
}
Get
Return fullNameValue
End Get
Set(ByVal value As String)
fullNameValue = value
End Set
End Property
End Class
3. DO make the serialization constructor protected and provide two parameters typed and named exactly as
shown in the sample here.
5. DO apply a link demand to ISerializable.GetObjectData implementation. This ensures that only fully
trusted core and the runtime serializer have access to the member.
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter)]
See Also
Using Data Contracts
Data Contract Serializer
Types Supported by the Data Contract Serializer
Binary Serialization
Remote Objects
XML and SOAP Serialization
Security and Serialization
How to: Chunk Serialized Data
4/14/2017 • 5 min to read • Edit Online
Two issues that occur when sending large data sets in Web service messages are:
1. A large working set (memory) due to buffering by the serialization engine.
2. Inordinate bandwidth consumption due to 33 percent inflation after Base64 encoding.
To solve these problems, implement the IXmlSerializable interface to control the serialization and deserialization.
Specifically, implement the WriteXml and ReadXml methods to chunk the data.
To implement server-side chunking
1. On the server machine, the Web method must turn off ASP.NET buffering and return a type that implements
IXmlSerializable.
2. The type that implements IXmlSerializable chunks the data in the WriteXml method.
To implement client-side processing
1. Alter the Web method on the client proxy to return the type that implements IXmlSerializable. You can use a
SchemaImporterExtension to do this automatically, but this is not shown here.
2. Implement the ReadXml method to read the chunked data stream and write the bytes to disk. This
implementation also raises progress events that can be used by a graphic control, such as a progress bar.
Example
The following code example shows the Web method on the client that turns off ASP.NET buffering. It also shows
the client-side implementation of the IXmlSerializable interface that chunks the data in the WriteXml method.
[WebMethod]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute
(ParameterStyle= SoapParameterStyle.Bare)]
public SongStream DownloadSong(DownloadAuthorization Authorization, string filePath)
{
End Function
End Class 'Test
[XmlSchemaProvider("MySchema")]
public class SongStream : IXmlSerializable
{
public SongStream(){ }
writer.Flush();
readLen = sr.Read(songBytes, 0, bufferSize);
}
writer.WriteEndElement();
inFile.Close();
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new System.NotImplementedException();
}
}
}
<XmlSchemaProvider("MySchema")> _
Public Class SongStream
Implements IXmlSerializable
End Sub
' This is the method named by the XmlSchemaProviderAttribute applied to the type.
Public Shared Function MySchema(ByVal xs As XmlSchemaSet) As XmlQualifiedName
' This method is called by the framework to get the schema for this type.
' We return an existing schema from disk.
Dim schemaSerializer As New XmlSerializer(GetType(XmlSchema))
Dim xsdPath As String = Nothing
' NOTE: replace SongStream.xsd with your own schema file.
xsdPath = System.Web.HttpContext.Current.Server.MapPath("SongStream.xsd")
Dim s As XmlSchema = CType(schemaSerializer.Deserialize(New XmlTextReader(xsdPath)), XmlSchema)
xs.XmlResolver = New XmlUrlResolver()
xs.Add(s)
End Function
writer.Flush()
readLen = sr.Read(songBytes, 0, bufferSize)
End While
writer.WriteEndElement()
inFile.Close()
End Sub
public SongFile()
{ }
string songBase64;
byte[] songBytes;
reader.ReadStartElement("song", ns);
double totalRead=0;
while(true)
{
if (reader.IsStartElement("chunk", ns))
{
songBase64 = reader.ReadElementString();
totalRead += songBase64.Length;
songBytes = Convert.FromBase64String(songBase64);
outFile.Write(songBytes, 0, songBytes.Length);
outFile.Flush();
if (OnProgress != null)
{
OnProgress(100 * (totalRead / size));
}
}
else
{
break;
}
}
outFile.Close();
reader.ReadEndElement();
}
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public void Play()
{
System.Diagnostics.Process.Start(this.filePath);
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new System.NotImplementedException();
}
End Sub
End Sub
End Sub
outFile.Close()
reader.ReadEndElement()
End Sub
See Also
Custom Serialization
XML and SOAP Serialization
4/14/2017 • 2 min to read • Edit Online
XML serialization converts (serializes) the public fields and properties of an object, or the parameters and return
values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD)
document. XML serialization results in strongly typed classes with public properties and fields that are
converted to a serial format (in this case, XML) for storage or transport.
Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless
of platform. For example, XML Web services created using ASP.NET use the XmlSerializer class to create XML
streams that pass data between XML Web service applications throughout the Internet or on intranets.
Conversely, deserialization takes such an XML stream and reconstructs the object.
XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification.
SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML.
To serialize or deserialize objects, use the XmlSerializer class. To create the classes to be serialized, use the XML
Schema Definition tool.
In This Section
Introducing XML Serialization
Provides a general definition of serialization, particularly XML serialization.
How to: Serialize an Object
Provides step-by-step instructions for serializing an object.
How to: Deserialize an Object
Provides step-by-step instructions for deserializing an object.
Examples of XML Serialization
Provides examples that demonstrate the basics of XML serialization.
The XML Schema Definition Tool and XML Serialization
Describes how to use the XML Schema Definition tool to create classes that adhere to a particular XML Schema
definition language (XSD) schema, or to generate an XML Schema from a .dll file.
Controlling XML Serialization Using Attributes
Describes how to control serialization by using attributes.
Attributes That Control XML Serialization
Lists the attributes that are used to control XML serialization.
How to: Specify an Alternate Element Name for an XML Stream
Presents an advanced scenario showing how to generate multiple XML streams by overriding the serialization.
How to: Control Serialization of Derived Classes
Provides an example of how to control the serialization of derived classes.
How to: Qualify XML Element and XML Attribute Names
Describes how to define and control the way in which XML namespaces are used in the XML stream.
XML Serialization with XML Web Services
Explains how XML serialization is used in XML Web services.
How to: Serialize an Object as a SOAP-Encoded XML Stream
Describes how to use the XmlSerializer class to create encoded SOAP XML streams that conform to section 5 of
the World Wide Web Consortium (www.w3.org) document titled "Simple Object Access Protocol (SOAP) 1.1."
How to: Override Encoded SOAP XML Serialization
Describes the process for overriding XML serialization of objects as SOAP messages.
Attributes That Control Encoded SOAP Serialization
Lists the attributes that are used to control SOAP-encoded serialization.
<system.xml.serialization> Element
The top-level configuration element for controlling XML serialization.
<dateTimeSerialization> Element
Controls the serialization mode of DateTime objects.
<schemaImporterExtensions> Element
Contains types that are used by the XmlSchemaImporter class.
<add> Element for <xmlSchemaImporterExtensions>
Adds types that are used by the XmlSchemaImporter class.
Related Sections
Advanced Development Technologies
Provides links to more information on sophisticated development tasks and techniques in the .NET Framework.
XML Web Services Created Using ASP.NET and XML Web Service Clients
Provides topics that describe and explain how to program XML Web services using ASP.NET.
See Also
Binary Serialization
How to: Control Serialization of Derived Classes
5/23/2017 • 4 min to read • Edit Online
Using the XmlElementAttribute attribute to change the name of an XML element is not the only way to
customize object serialization. You can also customize the XML stream by deriving from an existing class and
instructing the XmlSerializer instance how to serialize the new class.
For example, given a Book class, you can derive from it and create an ExpandedBook class that has a few more
properties. However, you must instruct the XmlSerializer to accept the derived type when serializing or
deserializing. This can be done by creating a XmlElementAttribute instance and setting its Type property to the
derived class type. Add the XmlElementAttribute to a XmlAttributes instance. Then add the XmlAttributes to a
XmlAttributeOverrides instance, specifying the type being overridden and the name of the member that accepts
the derived class. This is shown in the following example.
Example
Public Class Orders
public Books() As Book
End Class
' Adds the type of the class that contains the overridden
' member, as well as the XmlAttributes instance to override it
' with, to the XmlAttributeOverrides instance.
attrOverrides.Add(GetType(Orders), "Books", attrs)
See Also
XmlSerializer
XmlElementAttribute
XmlAttributes
XmlAttributeOverrides
XML and SOAP Serialization
How to: Serialize an Object
How to: Specify an Alternate Element Name for an XML Stream
Introducing XML Serialization
6/2/2017 • 10 min to read • Edit Online
Serialization is the process of converting an object into a form that can be readily transported. For example, you
can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other
end, deserialization reconstructs the object from the stream.
XML serialization serializes only the public fields and property values of an object into an XML stream. XML
serialization does not include type information. For example, if you have a Book object that exists in the Library
namespace, there is no guarantee that it is deserialized into an object of the same type.
NOTE
XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections).
To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML
serialization.
The central class in XML serialization is the XmlSerializer class, and the most important methods in this class are
the Serialize and Deserialize methods. The XmlSerializer creates C# files and compiles them into .dll files to
perform this serialization. In .NET Framework 2.0, the XML Serializer Generator Tool (Sgen.exe) is designed to
generate these serialization assemblies in advance to be deployed with your application and improve startup
performance. The XML stream generated by the XmlSerializer is compliant with the World Wide Web
Consortium (www.w3.org) XML Schema definition language (XSD) 1.0 recommendation. Furthermore, the data
types generated are compliant with the document titled "XML Schema Part 2: Datatypes."
The data in your objects is described using programming language constructs like classes, fields, properties,
primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. You have
the option of creating your own classes, annotated with attributes, or using the XML Schema Definition tool to
generate the classes based on an existing XML Schema.
If you have an XML Schema, you can run the XML Schema Definition tool to produce a set of classes that are
strongly typed to the schema and annotated with attributes. When an instance of such a class is serialized, the
generated XML adheres to the XML Schema. Provided with such a class, you can program against an easily
manipulated object model while being assured that the generated XML conforms to the XML schema. This is an
alternative to using other classes in the .NET Framework, such as the XmlReader and XmlWriter classes, to parse
and write an XML stream. For more information, see XML Documents and Data. These classes allow you to parse
any XML stream. In contrast, use the XmlSerializer when the XML stream is expected to conform to a known
XML Schema.
Attributes control the XML stream generated by the XmlSerializer class, allowing you to set the XML namespace,
element name, attribute name, and so on, of the XML stream. For more information about these attributes and
how they control XML serialization, see Controlling XML Serialization Using Attributes. For a table of those
attributes that are used to control the generated XML, see Attributes That Control XML Serialization.
The XmlSerializer class can further serialize an object and generate an encoded SOAP XML stream. The
generated XML adheres to section 5 of the World Wide Web Consortium document titled "Simple Object Access
Protocol (SOAP) 1.1." For more information about this process, see How to: Serialize an Object as a SOAP-
Encoded XML Stream. For a table of the attributes that control the generated XML, see Attributes That Control
Encoded SOAP Serialization.
The XmlSerializer class generates the SOAP messages created by, and passed to, XML Web services. To control
the SOAP messages, you can apply attributes to the classes, return values, parameters, and fields found in an XML
Web service file (.asmx). You can use both the attributes listed in "Attributes That Control XML Serialization" and
"Attributes That Control Encoded SOAP Serialization" because an XML Web service can use either the literal or
encoded SOAP style. For more information about using attributes to control the XML generated by an XML Web
service, see XML Serialization with XML Web Services. For more information about SOAP and XML Web services,
see Customizing SOAP Messages.
NOTE
These serialization assemblies can be generated in advance and signed by using the SGen.exe tool. This does not
work a server of Web services. In other words, it is only for client use and for manual serialization.
The code and the DLLs are vulnerable to a malicious process at the time of creation and compilation. When
using a computer running Microsoft Windows NT 4.0 or later, it might be possible for two or more users to
share the TEMP directory. Sharing a TEMP directory is dangerous if the two accounts have different
security privileges and the higher-privilege account runs an application using the XmlSerializer. In this
case, one user can breach the computer's security by replacing either the .cs or .dll file that is compiled. To
eliminate this concern, always be sure that each account on the computer has its own profile. By default,
the TEMP environment variable points to a different directory for each account.
If a malicious user sends a continuous stream of XML data to a Web server (a denial of service attack), then
the XmlSerializer continues to process the data until the computer runs low on resources.
This kind of attack is eliminated if you are using a computer running Internet Information Services (IIS),
and your application is running within IIS. IIS features a gate that does not process streams longer than a
set amount (the default is 4 KB). If you create an application that does not use IIS and deserializes with the
XmlSerializer, you should implement a similar gate that prevents a denial of service attack.
The XmlSerializer serializes data and runs any code using any type given to it.
There are two ways in which a malicious object presents a threat. It could run malicious code or it could
inject malicious code into the C# file created by the XmlSerializer. In the first case, if a malicious object
tries to run a destructive procedure, code access security helps prevent any damage from being done. In
the second case, there is a theoretical possibility that a malicious object may somehow inject code into the
C# file created by the XmlSerializer. Although this issue has been examined thoroughly, and such an
attack is considered unlikely, you should take the precaution of never serializing data with an unknown and
untrusted type.
Serialized sensitive data might be vulnerable.
After the XmlSerializerhas serialized data, it can be stored as an XML file or other data store. If your data
store is available to other processes, or is visible on an intranet or the Internet, the data can be stolen and
used maliciously. For example, if you create an application that serializes orders that include credit card
numbers, the data is highly sensitive. To help prevent this, always protect the store for your data and take
steps to keep it private.
<OrderForm>
<OrderDate>12/12/01</OrderDate>
</OrderForm>
NOTE
Only collections are serialized, not public properties.
XmlElement objects.
XmlNode objects.
DataSet objects.
For more information about serializing or deserializing objects, see How to: Serialize an Object and How to:
Deserialize an Object.
<XmlElement(DataType:="NMTOKEN")> _
Public MyToken As String
[XmlElement(DataType = "NMTOKEN")]
public string MyToken;
Similarly, if you are creating a class that must conform to a specific XML Schema (XSD), you should apply the
appropriate attribute and set its DataType property to the desired XML data type name.
For a complete list of type mappings, see the DataTypeproperty for any of the following attribute classes:
SoapAttributeAttribute
SoapElementAttribute
XmlArrayItemAttribute
XmlAttributeAttribute
XmlElementAttribute
XmlRootAttribute
See Also
XmlSerializer
DataContractSerializer
FileStream
XML and SOAP Serialization
Binary Serialization
Serialization
XmlSerializer
Examples of XML Serialization
How to: Serialize an Object
How to: Deserialize an Object
How to: Deserialize an Object
5/23/2017 • 1 min to read • Edit Online
When you deserialize an object, the transport format determines whether you will create a stream or file object.
After the transport format is determined, you can call the Serialize or Deserialize methods, as required.
To deserialize an object
1. Construct a XmlSerializer using the type of the object to deserialize.
2. Call the Deserialize method to produce a replica of the object. When deserializing, you must cast the
returned object to the type of the original, as shown in the following example, which deserializes the
object into a file (although it could also be deserialized into a stream).
MySerializableClass myObject;
// Construct an instance of the XmlSerializer with the type
// of object that is being deserialized.
XmlSerializer mySerializer =
new XmlSerializer(typeof(MySerializableClass));
// To read the file, create a FileStream.
FileStream myFileStream =
new FileStream("myFileName.xml", FileMode.Open);
// Call the Deserialize method and cast to the object type.
myObject = (MySerializableClass)
mySerializer.Deserialize(myFileStream)
See Also
Introducing XML Serialization
How to: Serialize an Object
Examples of XML Serialization
6/2/2017 • 14 min to read • Edit Online
XML serialization can take more than one form, from simple to complex. For example, you can serialize a class that
simply consists of public fields and properties, as shown in Introducing XML Serialization. The following code
examples address various advanced scenarios, including how to use XML serialization to generate an XML stream
that conforms to a specific XML Schema (XSD) document.
Serializing a DataSet
Besides serializing an instance of a public class, an instance of a DataSet can also be serialized, as shown in the
following code example.
<PurchaseOrder>
<Address>
<FirstName>George</FirstName>
</Address>
</PurchaseOrder>
The serialized class instance might resemble the following, if two items are ordered.
<PurchaseOrder xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Item>
<ItemID>aaa111</ItemID>
<ItemPrice>34.22</ItemPrice>
<Item>
<Item>
<ItemID>bbb222</ItemID>
<ItemPrice>2.89</ItemPrice>
<Item>
</Items>
</PurchaseOrder>
Serializing a Class that Implements the ICollection Interface
You can create your own collection classes by implementing the ICollection interface, and use the XmlSerializer to
serialize instances of these classes. Note that when a class implements the ICollection interface, only the collection
contained by the class is serialized. Any public properties or fields added to the class will not be serialized. The
class must include an Add method and an Item property (C# indexer) to be serialized.
Imports System
Imports System.IO
Imports System.Collections
Imports System.Xml.Serialization
End Property
return empArray.GetEnumerator()
End Function
Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports Microsoft.VisualBasic
' Calculate is a custom method that calculates the price per item
' and stores the value in a field.
Public Sub Calculate()
LineTotal = UnitPrice * Quantity
End Sub
End Class
// Creates an OrderedItem.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal) 5.23;
i1.Quantity = 3;
i1.Calculate();
See Also
Introducing XML Serialization
Controlling XML Serialization Using Attributes
Attributes That Control XML Serialization
XmlSerializer Class
How to: Serialize an Object
How to: Deserialize an Object
The XML Schema Definition Tool and XML
Serialization
4/14/2017 • 1 min to read • Edit Online
The XML Schema Definition tool (XML Schema Definition Tool (Xsd.exe)) is installed along with the .NET
Framework tools as part of the Windows® Software Development Kit (SDK). The tool is designed primarily for two
purposes:
To generate either C# or Visual Basic class files that conform to a specific XML Schema definition language
(XSD) schema. The tool takes an XML Schema as an argument and outputs a file that contains a number of
classes that, when serialized with the XmlSerializer, conform to the schema. For information about how to
use the tool to generate classes that conform to a specific schema, see How to: Use the XML Schema
Definition Tool to Generate Classes and XML Schema Documents.
To generate an XML Schema document from a .dll file or .exe file. To see the schema of a set of files that you
have either created or one that has been modified with attributes, pass the DLL or EXE as an argument to
the tool to generate the XML schema. For information about how to use the tool to generate an XML
Schema Document from a set of classes, see How to: Use the XML Schema Definition Tool to Generate
Classes and XML Schema Documents.
For more information about this tool and others, see Tools. For information about the tool's options, see XML
Schema Definition Tool (Xsd.exe).
See Also
DataSet
Introducing XML Serialization
XML Schema Definition Tool (Xsd.exe)
XmlSerializer
How to: Serialize an Object
How to: Deserialize an Object
How to: Use the XML Schema Definition Tool to Generate Classes and XML Schema Documents
XML Schema Binding Support in the .NET Framework
How to: Use the XML Schema Definition Tool to
Generate Classes and XML Schema Documents
6/2/2017 • 1 min to read • Edit Online
The XML Schema Definition tool (Xsd.exe) allows you to generate an XML schema that describes a class or to
generate the class defined by an XML schema. The following procedures show how to perform these operations.
To generate classes that conform to a specific schema
1. Open a command prompt.
2. Pass the XML Schema as an argument to the XML Schema Definition tool, which creates a set of classes that
are precisely matched to the XML Schema, for example:
xsd mySchema.xsd
The tool can only process schemas that reference the World Wide Web Consortium XML specification of
March 16, 2001. In other words, the XML Schema namespace must be
"http://www.w3.org/2001/XMLSchema" as shown in the following example.
3. Modify the classes with methods, properties, or fields, as necessary. For more information about modifying
a class with attributes, see Controlling XML Serialization Using Attributes and Attributes That Control
Encoded SOAP Serialization.
It is often useful to examine the schema of the XML stream that is generated when instances of a class (or classes)
are serialized. For example, you might publish your schema for others to use, or you might compare it to a schema
with which you are trying to achieve conformity.
To generate an XML Schema document from a set of classes
1. Compile the class or classes into a DLL.
2. Open a command prompt.
3. Pass the DLL as an argument to Xsd.exe, for example:
xsd MyFile.dll
The schema (or schemas) will be written, beginning with the name "schema0.xsd".
See Also
DataSet
The XML Schema Definition Tool and XML Serialization
Introducing XML Serialization
XML Schema Definition Tool (Xsd.exe)
XmlSerializer
How to: Serialize an Object
How to: Deserialize an Object
Controlling XML Serialization Using Attributes
6/2/2017 • 6 min to read • Edit Online
Attributes can be used to control the XML serialization of an object or to create an alternate XML stream from the
same set of classes. For more details about creating an alternate XML stream, see How to: Specify an Alternate
Element Name for an XML Stream.
NOTE
If the XML generated must conform to section 5 of the World Wide Web Consortium (www.w3.org) document titled
"Simple Object Access Protocol (SOAP) 1.1," use the attributes listed in Attributes That Control Encoded SOAP Serialization.
By default, an XML element name is determined by the class or member name. In a simple class named Book ,a
field named ISBN will produce an XML element tag <ISBN>, as shown in the following example.
This default behavior can be changed if you want to give the element a new name. The following code shows how
an attribute enables this by setting the ElementName property of a XmlElementAttribute.
For more information about attributes, see Attributes. For a list of attributes that control XML serialization, see
Attributes That Control XML Serialization.
<Group>
<Employees>
<Employee>
<Name>Haley</Name>
</Employee>
</Employees >
</Group>
By applying a XmlArrayAttribute, you can change the name of the XML element, as follows.
<Group>
<TeamMembers>
<Employee>
<Name>Haley</Name>
</Employee>
</TeamMembers>
The XmlArrayItemAttribute, on the other hand, controls how the items contained in the array are serialized. Note
that the attribute is applied to the field returning the array.
Public Class Group
<XmlArrayItem("MemberName")> _
Public Employee() As Employees
End Class
<Group>
<Employees>
<MemberName>Haley</MemberName>
</Employees>
</Group>
<Group>
<Employees>
<Name>Haley</Name>
</Employees>
<Employees>
<Name>Noriko</Name>
</Employees>
<Employees>
<Name>Marco</Name>
</Employees>
</Group>
Another way to differentiate the two XML streams is to use the XML Schema Definition tool to generate the XML
Schema (XSD) document files from the compiled code. (For more details on using the tool, see The XML Schema
Definition Tool and XML Serialization.) When no attribute is applied to the field, the schema describes the element
in the following manner.
When the XmlElementAttribute is applied to the field, the resulting schema describes the element as follows.
Serializing an ArrayList
The ArrayList class can contain a collection of diverse objects. You can therefore use a ArrayList much as you use
an array. Instead of creating a field that returns an array of typed objects, however, you can create a field that
returns a single ArrayList. However, as with arrays, you must inform the XmlSerializer of the types of objects the
ArrayList contains. To accomplish this, assign multiple instances of the XmlElementAttribute to the field, as shown
in the following example.
<XmlRoot("NewGroupName"), _
XmlType("NewTypeName")> _
Public Class Group
Public Employees() As Employee
End Class
[XmlRoot("NewGroupName")]
[XmlType("NewTypeName")]
public class Group{
public Employee[] Employees;
}
If this class is compiled, and the XML Schema Definition tool is used to generate its schema, you would find the
following XML describing Group .
In contrast, if you were to serialize an instance of the class, only NewGroupName would be found in the XML
document.
<NewGroupName>
. . .
</NewGroupName>
See Also
Attributes That Control XML Serialization
Attributes That Control Encoded SOAP Serialization
Introducing XML Serialization
Examples of XML Serialization
How to: Specify an Alternate Element Name for an XML Stream
How to: Serialize an Object
How to: Deserialize an Object
Attributes That Control XML Serialization
4/14/2017 • 2 min to read • Edit Online
You can apply the attributes in the following table to classes and class members to control the way in which the
XmlSerializer serializes or deserializes an instance of the class. To understand how these attributes control XML
serialization, see Controlling XML Serialization Using Attributes.
These attributes can also be used to control the literal style SOAP messages generated by an XML Web service.
For more information about applying these attributes to an XML Web services method, see XML Serialization with
XML Web Services.
For more information about attributes, see Attributes.
XmlAnyAttributeAttribute Public field, property, parameter, or When deserializing, the array will be
return value that returns an array of filled with XmlAttribute objects that
XmlAttribute objects. represent all XML attributes unknown
to the schema.
XmlAnyElementAttribute Public field, property, parameter, or When deserializing, the array is filled
return value that returns an array of with XmlElement objects that represent
XmlElement objects. all XML elements unknown to the
schema.
XmlArrayAttribute Public field, property, parameter, or The members of the array will be
return value that returns an array of generated as members of an XML
complex objects. array.
XmlArrayItemAttribute Public field, property, parameter, or The derived types that can be inserted
return value that returns an array of into an array. Usually applied in
complex objects. conjunction with an XmlArrayAttribute.
XmlElementAttribute Public field, property, parameter, or The field or property will be serialized
return value. as an XML element.
XmlIgnoreAttribute Public properties and fields. The property or field should be ignored
when the containing class is serialized.
XmlIncludeAttribute Public derived class declarations, and The class should be included when
return values of public methods for generating schemas (to be recognized
Web Services Description Language when serialized).
(WSDL) documents.
ATTRIBUTE APPLIES TO SPECIFIES
XmlTypeAttribute Public class declarations. The name and namespace of the XML
type.
In addition to these attributes, which are all found in the System.Xml.Serialization namespace, you can also apply
the DefaultValueAttribute attribute to a field. The DefaultValueAttribute sets the value that will be automatically
assigned to the member if no value is specified.
To control encoded SOAP XML serialization, see Attributes That Control Encoded SOAP Serialization.
See Also
XML and SOAP Serialization
XmlSerializer
Controlling XML Serialization Using Attributes
How to: Specify an Alternate Element Name for an XML Stream
How to: Serialize an Object
How to: Deserialize an Object
How to: Specify an Alternate Element Name for an
XML Stream
6/2/2017 • 2 min to read • Edit Online
Code Example
Using the XmlSerializer, you can generate more than one XML stream with the same set of classes. You might
want to do this because two different XML Web services require the same basic information, with only slight
differences. For example, imagine two XML Web services that process orders for books, and thus both require
ISBN numbers. One service uses the tag <ISBN> while the second uses the tag <BookID>. You have a class
named Book that contains a field named ISBN . When an instance of the Book class is serialized, it will, by
default, use the member name (ISBN) as the tag element name. For the first XML Web service, this is as expected.
But to send the XML stream to the second XML Web service, you must override the serialization so that the tag's
element name is BookID .
To create an XML stream with an alternate element name
1. Create an instance of the XmlElementAttribute class.
2. Set the ElementName of the XmlElementAttribute to "BookID".
3. Create an instance of the XmlAttributes class.
4. Add the XmlElementAttribute object to the collection accessed through the XmlElements property of
XmlAttributes .
5. Create an instance of the XmlAttributeOverrides class.
6. Add the XmlAttributes to the XmlAttributeOverrides, passing the type of the object to override and the
name of the member being overridden.
7. Create an instance of the XmlSerializer class with XmlAttributeOverrides .
8. Create an instance of the Book class, and serialize or deserialize it.
Example
Public Class SerializeOverride()
' Creates an XmlElementAttribute with the alternate name.
Dim myElementAttribute As XmlElementAttribute = _
New XmlElementAttribute()
myElementAttribute.ElementName = "BookID"
Dim myAttributes As XmlAttributes = New XmlAttributes()
myAttributes.XmlElements.Add(myElementAttribute)
Dim myOverrides As XmlAttributeOverrides = New XmlAttributeOverrides()
myOverrides.Add(typeof(Book), "ISBN", myAttributes)
Dim mySerializer As XmlSerializer = _
New XmlSerializer(GetType(Book), myOverrides)
Dim b As Book = New Book()
b.ISBN = "123456789"
' Creates a StreamWriter to write the XML stream to.
Dim writer As StreamWriter = New StreamWriter("Book.xml")
mySerializer.Serialize(writer, b);
End Class
public class SerializeOverride()
{
// Creates an XmlElementAttribute with the alternate name.
XmlElementAttribute myElementAttribute = new XmlElementAttribute();
myElementAttribute.ElementName = "BookID";
XmlAttributes myAttributes = new XmlAttributes();
myAttributes.XmlElements.Add(myElementAttribute);
XmlAttributeOverrides myOverrides = new XmlAttributeOverrides();
myOverrides.Add(typeof(Book), "ISBN", myAttributes);
XmlSerializer mySerializer =
new XmlSerializer(typeof(Book), myOverrides)
Book b = new Book();
b.ISBN = "123456789"
// Creates a StreamWriter to write the XML stream to.
StreamWriter writer = new StreamWriter("Book.xml");
mySerializer.Serialize(writer, b);
}
<Book>
<BookID>123456789</BookID>
</Book>
See Also
XmlElementAttribute
XmlAttributes
XmlAttributeOverrides
XML and SOAP Serialization
XmlSerializer
How to: Serialize an Object
How to: Deserialize an Object
How to: Deserialize an Object
How to: Serialize an Object
4/14/2017 • 1 min to read • Edit Online
To serialize an object, first create the object that is to be serialized and set its public properties and fields. To do
this, you must determine the transport format in which the XML stream is to be stored, either as a stream or as
a file. For example, if the XML stream must be saved in a permanent form, create a FileStream object.
NOTE
For more examples of XML serialization, see Examples of XML Serialization.
To serialize an object
1. Create the object and set its public fields and properties.
2. Construct a XmlSerializer using the type of the object. For more information, see the XmlSerializer class
constructors.
3. Call the Serialize method to generate either an XML stream or a file representation of the object's public
properties and fields. The following example creates a file.
See Also
Introducing XML Serialization
How to: Deserialize an Object
How to: Qualify XML Element and XML Attribute
Names
5/23/2017 • 3 min to read • Edit Online
Code Example
XML namespaces contained by instances of the XmlSerializerNamespaces class must conform to the World Wide
Web Consortium (www.w3.org) specification called "Namespaces in XML."
XML namespaces provide a method for qualifying the names of XML elements and XML attributes in XML
documents. A qualified name consists of a prefix and a local name, separated by a colon. The prefix functions only
as a placeholder; it is mapped to a URI that specifies a namespace. The combination of the universally managed
URI namespace and the local name produces a name that is guaranteed to be universally unique.
By creating an instance of XmlSerializerNamespaces and adding the namespace pairs to the object, you can specify
the prefixes used in an XML document.
To create qualified names in an XML document
1. Create an instance of the XmlSerializerNamespaces class.
2. Add all prefixes and namespace pairs to the XmlSerializerNamespaces .
3. Apply the appropriate System.Xml.Serialization attribute to each member or class that the XmlSerializer is
to serialize into an XML document.
The available attributes are: XmlAnyElementAttribute, XmlArrayAttribute, XmlArrayItemAttribute,
XmlAttributeAttribute, XmlElementAttribute, XmlRootAttribute, and XmlTypeAttribute.
4. Set the property of each attribute to one of the namespace values from the
Namespace
XmlSerializerNamespaces .
Example
The following example creates an XmlSerializerNamespaces , and adds two prefix and namespace pairs to the object.
The code creates an XmlSerializer that is used to serialize an instance of the Books class. The code calls the
Serialize method with the XmlSerializerNamespaces , allowing the XML to contain prefixed namespaces.
Option Explicit
public class Price
{
[XmlAttribute(Namespace = "http://www.cpandl.com")]
public string currency;
[XmlElement(Namespace = "http://www.cohowinery.com")]
public decimal price;
}
Option Strict
Imports System
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Public Class Run
<XmlType([Namespace] := "http://www.cpandl.com")> _
Public Class Book
<XmlElement([Namespace] := "http://www.cpandl.com")> _
Public TITLE As String
<XmlElement([Namespace] := "http://www.cohowinery.com")> _
Public PRICE As Price
End Class
// Creates a Book.
Book myBook = new Book();
myBook.TITLE = "A Book Title";
Price myPrice = new Price();
myPrice.price = (decimal) 9.95;
myPrice.currency = "US Dollar";
myBook.PRICE = myPrice;
Books myBooks = new Books();
myBooks.Book = myBook;
mySerializer.Serialize(myWriter,myBooks,myNamespaces);
myWriter.Close();
}
}
[XmlType(Namespace ="http://www.cpandl.com")]
public class Book
{
[XmlElement(Namespace = "http://www.cpandl.com")]
public string TITLE;
[XmlElement(Namespace ="http://www.cohowinery.com")]
public Price PRICE;
}
See Also
XmlSerializer
The XML Schema Definition Tool and XML Serialization
Introducing XML Serialization
XmlSerializer Class
Attributes That Control XML Serialization
How to: Specify an Alternate Element Name for an XML Stream
How to: Serialize an Object
How to: Deserialize an Object
XML Serialization with XML Web Services
6/2/2017 • 5 min to read • Edit Online
XML serialization is the underlying transport mechanism used in the XML Web services architecture, performed by
the XmlSerializer class. To control the XML generated by an XML Web service, you can apply the attributes listed in
both Attributes That Control XML Serialization and Attributes That Control Encoded SOAP Serialization to the
classes, return values, parameters, and fields of a file used to create an XML Web service (.asmx). For more
information about creating an XML Web service, see Building XML Web Services Using ASP.NET.
The following code example calls MyLiteralMethod . The element name is changed to "LiteralOrderID".
The following code example calls MyEncodedMethod . The element name is "EncodedOrderID".
When invoked, the code returns XML that resembles the following.
<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod(<XmlElement _
("MyOrderID", Namespace:="http://www.microsoft.com")>ID As String) As _
<XmlElement(Namespace:="http://www.cohowinery.com", _
ElementName:= "BookOrder")> _
Order
Dim myOrder As Order = New Order()
myOrder.OrderID = ID
return myOrder
End Function
<XmlType("BigBookService"), _
SoapType("SoapBookService"), _
XmlRoot("BookOrderForm")> _
Public Class Order
' Both types of attributes can be applied. Depending on which
' the method used, either one will affect the call.
<SoapElement(ElementName:= "EncodedOrderID"), _
XmlElement(ElementName:= "LiteralOrderID")> _
public OrderID As String
End Class
The results of applying the XmlTypeAttribute and SoapTypeAttribute can be seen when you examine the service
description, as shown in the following code example.
- <s:schema targetNamespace="http://tempuri.org/encodedTypes">
- <s:complexType name="SoapBookService">
- <s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="EncodedOrderID" type="s:string" />
</s:sequence>
</s:complexType>
</s:schema>
The effect of the XmlRootAttribute can also be seen in the HTTP GET and HTTP POST results, as follows.
<?xml version="1.0" encoding="utf-8"?>
<BookOrderForm xmlns="http://tempuri.org/">
<LiteralOrderID>string</LiteralOrderID>
</BookOrderForm>
See Also
XML and SOAP Serialization
Attributes That Control Encoded SOAP Serialization
How to: Serialize an Object as a SOAP-Encoded XML Stream
How to: Override Encoded SOAP XML Serialization
Introducing XML Serialization
How to: Serialize an Object
How to: Deserialize an Object
How to: Serialize an Object as a SOAP-Encoded
XML Stream
5/23/2017 • 1 min to read • Edit Online
Code Example
Because a SOAP message is built using XML, the XmlSerializer can be used to serialize classes and generate
encoded SOAP messages. The resulting XML conforms to section 5 of the World Wide Web Consortium
(www.w3.org) document "Simple Object Access Protocol (SOAP) 1.1". When you are creating an XML Web service
that communicates through SOAP messages, you can customize the XML stream by applying a set of special
SOAP attributes to classes and members of classes. For a list of attributes, see Attributes That Control Encoded
SOAP Serialization.
To serialize an object as a SOAP-encoded XML stream
1. Create the class using the XML Schema Definition Tool (Xsd.exe).
2. Apply one or more of the special attributes found in System.Xml.Serialization . See the list in "Attributes
That Control Encoded SOAP Serialization."
3. Create an XmlTypeMapping by creating a new SoapReflectionImporter , and invoking the ImportTypeMapping
method with the type of the serialized class.
The following code example calls the ImportTypeMapping method of the SoapReflectionImporter class to
create an XmlTypeMapping .
Example
' Serializes a class named Group as a SOAP message.
Dim myTypeMapping As XmlTypeMapping = (New SoapReflectionImporter(). _
ImportTypeMapping(GetType(Group))
Dim mySerializer As XmlSerializer = New XmlSerializer(myTypeMapping)
See Also
XML and SOAP Serialization
Attributes That Control Encoded SOAP Serialization
XML Serialization with XML Web Services
How to: Serialize an Object
How to: Deserialize an Object
How to: Override Encoded SOAP XML Serialization
How to: Override Encoded SOAP XML Serialization
4/14/2017 • 4 min to read • Edit Online
Code Example
The process for overriding XML serialization of objects as SOAP messages is similar to the process for overriding
standard XML serialization. For information about overriding standard XML serialization, see How to: Specify an
Alternate Element Name for an XML Stream.
To override serialization of objects as SOAP messages
1. Create an instance of the SoapAttributeOverrides class.
2. Create a SoapAttributes for each class member that is being serialized.
3. Create an instance of one or more of the attributes that affect XML serialization, as appropriate, to the
member being serialized. For more information, see "Attributes That Control Encoded SOAP Serialization".
4. Set the appropriate property of SoapAttributes to the attribute created in step 3.
5. Add SoapAttributes to SoapAttributeOverrides .
6. Create an XmlTypeMapping using the SoapAttributeOverrides . Use the
SoapReflectionImporter.ImportTypeMapping method.
7. Create an XmlSerializer using XmlTypeMapping .
8. Serialize or deserialize the object.
Example
The following code example serializes a file in two ways: first, without overriding the XmlSerializer class's
behavior, and second, by overriding the behavior. The example contains a class named Group with several
members. Various attributes, such as the SoapElementAttribute , have been applied to class members. When the
class is serialized with the SerializeOriginal method, the attributes control the SOAP message content. When the
SerializeOverride method is called, the behavior of the XmlSerializer is overridden by creating various
attributes and setting the properties of a SoapAttributes to those attributes (as appropriate).
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
[SoapAttribute(DataType = "base64Binary")]
public Byte [] GroupNumber;
[SoapInclude(typeof(Car))]
public Vehicle myCar(string licNumber)
{
Vehicle v;
if(licNumber == "")
{
v = new Car();
v.licenseNumber = "!!!!!!";
}
else
{
v = new Car();
v.licenseNumber = licNumber;
}
return v;
}
}
}
public void SerializeOriginal(string filename)
{
// Creates an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);
myGroup.PostitiveInt= "10000";
myGroup.IgnoreThis=true;
myGroup.Grouptype= GroupType.small;
Car thisCar =(Car) myGroup.myCar("1234566");
// Prints the license number just to prove the car was created.
Console.WriteLine("License#: " + thisCar.licenseNumber + "\n");
myGroup.PostitiveInt= "10000";
myGroup.IgnoreThis=true;
myGroup.Grouptype= GroupType.small;
Car thisCar =(Car) myGroup.myCar("1234566");
Console.WriteLine(myGroup.GroupName);
Console.WriteLine(myGroup.GroupNumber[0]);
Console.WriteLine(myGroup.GroupNumber[1]);
Console.WriteLine(myGroup.GroupNumber[1]);
Console.WriteLine(myGroup.Today);
Console.WriteLine(myGroup.PostitiveInt);
Console.WriteLine(myGroup.IgnoreThis);
Console.WriteLine();
}
Console.WriteLine(myGroup.GroupName);
Console.WriteLine(myGroup.GroupNumber[0]);
Console.WriteLine(myGroup.GroupNumber[1]);
Console.WriteLine(myGroup.Today);
Console.WriteLine(myGroup.PostitiveInt);
Console.WriteLine(myGroup.IgnoreThis);
}
See Also
XML and SOAP Serialization
Attributes That Control Encoded SOAP Serialization
XML Serialization with XML Web Services
How to: Serialize an Object
How to: Deserialize an Object
How to: Serialize an Object as a SOAP-Encoded XML Stream
Attributes That Control Encoded SOAP Serialization
4/14/2017 • 1 min to read • Edit Online
The World Wide Web Consortium (www.w3.org) document named "Simple Object Access Protocol (SOAP) 1.1"
contains an optional section (section 5) that describes how SOAP parameters can be encoded. To conform to
section 5 of the specification, you must use a special set of attributes found in the System.Xml.Serialization
namespace. Apply those attributes as appropriate to classes and members of classes, and then use the
XmlSerializer to serialize instances of the class or classes.
The following table shows the attributes, where they can be applied, and what they do. For more information
about using these attributes to control XML serialization, see How to: Serialize an Object as a SOAP-Encoded
XML Stream and How to: Override Encoded SOAP XML Serialization.
For more information about attributes, see Attributes.
SoapAttributeAttribute Public field, property, parameter, or The class member will be serialized as
return value. an XML attribute.
SoapElementAttribute Public field, property, parameter, or The class will be serialized as an XML
return value. element.
SoapIncludeAttribute Public-derived class declarations and The type should be included when
public methods for Web Services generating schemas (to be recognized
Description Language (WSDL) when serialized).
documents.
See Also
XML and SOAP Serialization
How to: Serialize an Object as a SOAP-Encoded XML Stream
How to: Override Encoded SOAP XML Serialization
Attributes
XmlSerializer
How to: Serialize an Object
How to: Deserialize an Object
<system.xml.serialization> Element
6/2/2017 • 1 min to read • Edit Online
The top-level element for controlling XML serialization. For more information about configuration files, see
Configuration File Schema.
<configuration>
<system.xml.serialization>
Syntax
<system.xml.serialization>
</system.xml.serialization>
<schemaImporterExtensions> Element Contains types that are used by the XmlSchemaImporter for
mapping of XSD types to .NET Framework types.
Parent Elements
ELEMENT DESCRIPTION
<configuration> Element The root element in every configuration file that is used by
the common language runtime and .NET Framework
applications.
Example
The following code example illustrates how to specify the serialization mode of a DateTime object, and the
addition of types used by the XmlSchemaImporter when mapping XSD types to .NET Framework types.
<system.xml.serialization>
<xmlSerializer checkDeserializeAdvances="false" />
<dateTimeSerialization mode = "Local" />
<schemaImporterExtensions>
<add
name = "MobileCapabilities"
type = "System.Web.Mobile.MobileCapabilities,
System.Web.Mobile, Version - 2.0.0.0, Culture = neuutral,
PublicKeyToken = b03f5f6f11d40a3a" />
</schemaImporterExtensions>
</system.sxml.serialization>
See Also
XmlSchemaImporter
DateTimeSerializationSection.DateTimeSerializationMode
Configuration File Schema
<dateTimeSerialization> Element
<schemaImporterExtensions> Element
<add> Element for <xmlSchemaImporterExtensions>
<dateTimeSerialization> Element
6/2/2017 • 1 min to read • Edit Online
Syntax
<dateTimeSerialization
mode = "Roundtrip" | "Local"
/>
Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION
Remarks
In versions 1.0, 1.1, 2.0 and later versions of the .NET Framework, when this property is set to Local, DateTime
objects are always formatted as the local time. That is, local time zone information is always included with the
serialized data. Set this property to Local to ensure compatibility with older versions of the .NET Framework.
In version 2.0 and later versions of the .NET Framework that have this property set to Roundtrip, DateTime
objects are examined to determine whether they are in the local, UTC, or an unspecified time zone. The DateTime
objects are then serialized in such a way that this information is preserved. This is the default behavior and is the
recommended behavior for all new applications that do not communicate with older versions of the framework.
See Also
DateTime
XmlSchemaImporter
DateTimeSerializationSection.DateTimeSerializationMode
Configuration File Schema
<schemaImporterExtensions> Element
<add> Element for <xmlSchemaImporterExtensions>
<system.xml.serialization> Element
<schemaImporterExtensions> Element
6/2/2017 • 1 min to read • Edit Online
Contains types that are used by the XmlSchemaImporter for mapping of XSD types to .NET Framework types. For
more information about configuration files, see Configuration File Schema.
Syntax
<schemaImporterExtensions>
<!-- Add types -->
</SchemaImporterExtension>
Child Elements
ELEMENT DESCRIPTION
<add> Element for <xmlSchemaImporterExtensions> Adds types that are used by the XmlSchemaImporter to
create mappings.
Parent Elements
ELEMENT DESCRIPTION
Example
The following code example illustrates how to add types that are used by the XmlSchemaImporter when mapping
XSD types to .NET Framework types.
<system.xml.serialization>
<schemaImporterExtensions>
<add name = "MobileCapabilities" type =
"System.Web.Mobile.MobileCapabilities,
System.Web.Mobile, Version - 2.0.0.0, Culture = neutral,
PublicKeyToken = b03f5f6f11d40a3a" />
</schemaImporterExtensions>
/system.sxml.serializaiton>
See Also
XmlSchemaImporter
DateTimeSerializationSection.DateTimeSerializationMode
Configuration File Schema
<dateTimeSerialization> Element
<add> Element for <xmlSchemaImporterExtensions>
<system.xml.serialization> Element
<add> Element for
<xmlSchemaImporterExtensions>
6/2/2017 • 1 min to read • Edit Online
Adds types used by the XmlSchemaImporter for mapping XSD types to .NET Framework types. For more
information about configuration files, see Configuration File Schema.
<configuration>
<system.xml.serialization>
<XmlSchemaImporterExtensions>
<add>
Syntax
<add name = "typeName" type="fully qualified type [,Version=version number] [,Culture=culture]
[,PublicKeyToken= token]"/>
Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION
Example
The following code example adds an extension type that the XmlSchemaImporter can use when mapping types.
<configuration>
<system.xml.serialization>
<xmlSchemaImporterExtensions>
<add name="contoso" type="System.Web.Mobile.MobileCapabilities,
System.Web.Mobile, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</xmlSchemaImporterExtensions>
</system.xml.serialization>
</configuration>
See Also
XmlSchemaImporter
<system.xml.serialization> Element
<schemaImporterExtensions> Element
<xmlSerializer> Element
6/2/2017 • 1 min to read • Edit Online
Syntax
<xmlSerializer checkDeserializerAdvance = "true"|"false" />
Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION
Remarks
By default, the XmlSerializer provides an additional layer of security against potential denial of service attacks when
deserializing untrusted data. It does so by attempting to detect infinite loops during deserialization. If such a
condition is detected, an exception is thrown with the following message: "Internal error: deserialization failed to
advance over underlying stream."
Receiving this message does not necessarily indicate that a denial of service attack is in progress. In some rare
circumstances, the infinite loop detection mechanism produces a false positive and the exception is thrown for a
legitimate incoming message. If you find that in your particular application legitimate messages are being rejected
by this extra layer of protection, set checkDeserializeAdvances attribute to "false".
Example
The following code example sets the checkDeserializeAdvances attribute to "false".
<configuration>
<system.xml.serialization>
<xmlSerializer checkDeserializeAdvances="false" />
</system.xml.serialization>
</configuration>
See Also
XmlSerializer
<system.xml.serialization> Element
XML and SOAP Serialization
Serialization Tools
4/14/2017 • 1 min to read • Edit Online
This section contains detailed information about the serialization tools. You can run all the tools from the command
line.
IMPORTANT
For the .NET Framework tools to function properly, you must set your Path, Include, and Lib environment variables correctly.
Set these environment variables by running SDKVars.bat, which is located in the <SDK>\v2.0\Bin directory. SDKVars.bat must
be executed in every command shell.
In This Section
TOOL DESCRIPTION
XML Serializer Generator Tool (Sgen.exe) Creates an XML serialization assembly for types in a specified
assembly in order to improve the run-time performance of the
XmlSerializer.
XML Schema Definition Tool (Xsd.exe) Generates XML schemas that follow the XSD language
proposed by the World Wide Web Consortium (W3C). This
tool generates common language runtime classes and DataSet
classes from an XSD schema file.
See Also
Tools
XML Serializer Generator Tool (Sgen.exe)
5/23/2017 • 2 min to read • Edit Online
The XML Serializer Generator creates an XML serialization assembly for types in a specified assembly in order to
improve the startup performance of a XmlSerializer when it serializes or deserializes objects of the specified types.
Syntax
sgen [options]
Parameters
OPTION DESCRIPTION
/a[ssembly]:filename Generates serialization code for all the types contained in the
assembly or executable specified by filename. Only one file
name can be provided. If this argument is repeated, the last
file name is used.
/c[ompiler]: options Specifies the options to pass to the C# compiler. All csc.exe
options are supported as they are passed to the compiler. This
can be used to specify that the assembly should be signed
and to specify the key file.
/p[roxytypes] Generates serialization code only for the XML Web service
proxy types.
/v[erbose] Displays verbose output for debugging. Lists types from the
target assembly that cannot be serialized with the
XmlSerializer.
Remarks
When the XML Serializer Generator is not used, a XmlSerializer generates serialization code and a serialization
assembly for each type every time an application is run. To improve the performance of XML serialization startup,
use the Sgen.exe tool to generate those assemblies the assemblies in advance. These assemblies can then be
deployed with the application.
The XML Serializer Generator can also improve the performance of clients that use XML Web service proxies to
communicate with servers because the serialization process will not incur a performance hit when the type is
loaded the first time.
These generated assemblies cannot be used on the server side of a Web service. This tool is only for Web service
clients and manual serialization scenarios.
If the assembly containing the type to serialize is named MyType.dll, then the associated serialization assembly will
be named MyType.XmlSerializers.dll.
Examples
The following command creates an assembly named Data.XmlSerializers.dll for serializing all the types contained
in the assembly named Data.dll.
sgen Data.dll
The Data.XmlSerializers.dll assembly can be referenced from code that needs to serialize and deserialize the types
in Data.dll.
See Also
Tools
XML Web Services Overview
Command Prompts
XML Schema Definition Tool (Xsd.exe)
6/2/2017 • 8 min to read • Edit Online
The XML Schema Definition (Xsd.exe) tool generates XML schema or common language runtime classes from
XDR, XML, and XSD files, or from classes in a runtime assembly.
Syntax
xsd file.xdr [/outputdir:directory][/parameters:file.xml]
xsd file.xml [/outputdir:directory] [/parameters:file.xml]
xsd file.xsd {/classes | /dataset} [/element:element]
[/enableLinqDataSet] [/language:language]
[/namespace:namespace] [/outputdir:directory] [URI:uri]
[/parameters:file.xml]
xsd {file.dll | file.exe} [/outputdir:directory] [/type:typename [...]][/parameters:file.xml]
Argument
ARGUMENT DESCRIPTION
file.extension Specifies the input file to convert. You must specify the
extensionas one of the following: .xdr, .xml, .xsd, .dll, or .exe.
General Options
OPTION DESCRIPTION
/o[utputdir]:directory Specifies the directory for output files. This argument can
appear only once. The default is the current directory.
/P[arameters]: file.xml Read options for various operation modes from the specified
.xml file. The short form is '/p:'. For more information, see the
following Remarks section.
OPTION DESCRIPTION
You can also specify any of the following options for .xsd files.
OPTION DESCRIPTION
/enableLinqDataSet (Short form: /eld .) Specifies that the generated DataSet can
be queried against using LINQ to DataSet. This option is used
when the /dataset option is also specified. For more
information, see LINQ to DataSet Overview and Querying
Typed DataSets. For general information about using LINQ,
see LINQ (Language-Integrated Query).
/n[amespace]:namespace Specifies the runtime namespace for the generated types. The
default namespace is Schemas .
OPTION DESCRIPTION
/o[ut]: directoryName Specifies the output directory to place the files in. The default
is the current directory.
/u[ri]:uri Specifies the URI for the elements in the schema to generate
code for. This URI, if present, applies to all elements specified
with the /element option.
/t[ype]:typename Specifies the name of the type to create a schema for. 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
option, Xsd.exe generates schemas for all types in the
assembly.
Remarks
The following table shows the operations that Xsd.exe performs.
XDR to XSD
Generates an XML schema from an XML-Data-Reduced schema file. XDR is an early XML-based schema format.
XML to XSD
Generates an XML schema from an XML file.
XSD to DataSet
Generates common language runtime DataSet classes from an XSD schema file. The generated classes provide a
rich object model for regular XML data.
XSD to Classes
Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with
System.Xml.Serialization.XmlSerializer to read and write XML code that follows the schema.
Classes to XSD
Generates an XML schema from a type or types in a runtime assembly file. The generated schema defines the
XML format used by System.Xml.Serialization.XmlSerializer .
Xsd.exe only allows you to manipulate XML schemas that follow the XML Schema Definition (XSD) language
proposed by the World Wide Web Consortium (W3C). For more information on the XML Schema Definition
proposal or the XML standard, see http://w3.org.
If the preceding XML is contained in a file named GenerateSchemas.xml, then use the /parameters switch by
typing the following at a command prompt and pressing ENTER:
xsd /p:GenerateSchemas.xml
On the other hand, if you are generating a schema for a single type found in the assembly, you can use the
following XML:
But to use preceding code, you must also supply the name of the assembly at the command prompt. Type the
following at a command prompt (presuming the XML file is named GenerateSchemaFromType.xml):
xsd /p:GenerateSchemaFromType.xml ConsoleApplication1.exe
You must specify only one of the following options for the \<generateSchemas> element.
ELEMENT DESCRIPTION
To generate a code file, use the <generateClasses\> element. The following example generates a code file. Note
that two attributes are also shown that allow you to set the programming language and namespace of the
generated file.
<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
<generateClasses language='VB' namespace='Microsoft.Serialization.Examples'/>
</xsd>
<!-- You must supply an .xsd file when typing in the command line.-->
<!-- For example: xsd /p:genClasses mySchema.xsd -->
Options you can set for the \<generateClasses> element include the following.
ELEMENT DESCRIPTION
The following table shows the attributes that can also be used with the <generateClasses\> element.
ATTRIBUTE DESCRIPTION
You can also control how DataSet code is generated by using the <generateDataSets\> element. The following
XML specifies that the generated codeuses DataSet structures (such as the DataTable class) to create Visual Basic
code for a specified element. The generated DataSet structures will support LINQ queries.
<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
</generateDataSet>
</xsd>
Options you can set for the <generateDataSet\> element include the following.
ELEMENT DESCRIPTION
The following table shows the attributes that can be used with the <generateDataSet\> element.
ATTRIBUTE DESCRIPTION
There are attributes that you can set on the top level <xsd\> element. These options can be used with any of the
child elements ( <generateSchemas\> , <generateClasses\> or <generateDataSet\> ). The following XML code
generates code for an element named "IDItems" in the output directory named "MyOutputDirectory".
The following table shows the attributes that can also be used with the \<xsd> element.
ATTRIBUTE DESCRIPTION
help Displays command syntax and options for the tool. Set to
true or false .
Examples
The following command generates an XML schema from myFile.xdr and saves it to the current directory.
xsd myFile.xdr
The following command generates an XML schema from myFile.xml and saves it to the specified directory.
The following command generates a data set that corresponds to the specified schema in the C# language and
saves it as XSDSchemaFile.cs in the current directory.
The following command generates XML schemas for all types in the assembly myAssembly.dll and saves them as
schema0.xsd in the current directory.
xsd myAssembly.dll
See Also
DataSet
System.Xml.Serialization.XmlSerializer
Tools
Command Prompts
LINQ to DataSet Overview
Querying Typed DataSets
LINQ (Language-Integrated Query)
Serialization Samples for the .NET Framework
4/14/2017 • 1 min to read • Edit Online
In This Section
Basic Serialization Technology Sample
Demonstrates how to serialize an object graph in memory to a stream.
Version Tolerant Serialization Technology Sample
Demonstrates the version tolerance features of .NET Serialization.
Web Services Generics Serialization Technology Sample
Shows how to use and control the serialization of generics in ASP.NET Web Services.
Web Services IXmlSerializable Technology Sample
Shows how to use IXmlSerializable to control the serialization of custom types in ASP.NET Web Services.
SchemaImporterExtension Technology Sample
Demonstrates a custom SchemaImporterExtension.
Custom Serialization Order With XmlSerializer
Shows how to control the order of serialized and deserialized elements for XML serialization.
Related Sections
Serialization
Basic Serialization Technology Sample
4/14/2017 • 2 min to read • Edit Online
Download sample
This sample demonstrates the common language runtime's ability to serialize an object graph in memory to a
stream. This sample can use either the SoapFormatter or the BinaryFormatter for serialization. A linked list, filled
with data, is serialized or deserialized to or from a file stream. In either case the list is displayed so that you can see
the results. The linked list is of type LinkedList , a type defined by this sample.
Review comments in the source code and build.proj files for more information on serialization.
To build the sample using the Command Prompt
1. Navigate to one of the language-specific subdirectories under the Technologies\Serialization\Runtime
Serialization\Basic directory, using the command prompt.
2. Type msbuild SerializationCS.sln, msbuild SerializationJSL.sln or msbuild SerializationVB.sln,
depending on your choice of programming language, at the command line.
To build the sample using Visual Studio
1. Open File Explorer and navigate to one of the language-specific subdirectories for the sample.
2. Double-click the icon for the SerializationCS.sln, SerializationJSL.sln or SerializationVB.sln file, depending on
your choice of programming language, to open the file in Visual Studio.
3. In the Build menu, select Build Solution.
The sample application will be built in the default \bin or \bin\Debug subdirectory.
To run the sample
1. Navigate to the directory containing the built executable.
2. Type Serialization.exe, along with the parameter values you desire, at the command line.
NOTE
This sample builds a console application. You must launch it using the command prompt in order to view its output.
Remarks
The sample application accepts command line parameters indicating which test you would like to execute. To
serialize a 10-node list to a file named Test.xml using the SOAP formatter, use the parameters sx Test.xml 10.
For Example:
Serialize.exe -sx Test.xml 10
To deserialize the Test.xml file from the previous example, use the parameters dx Test.xml.
For Example:
Serialize.exe -dx Test.xml
In the two examples above, the "x" in the command line switch indicates that you want XML SOAP serialization. You
can use "b" in its place to use binary serialization. If you wish to try serialization with a very large number of nodes,
you might want to redirect the console output to a file.
For Example:
Serialize.exe -sb Test.bin 10000 >somefile.txt
The following bullets briefly describe the classes and technologies used by this sample.
Runtime Serialization
IFormatter Used to refer to either a BinaryFormatter or a SoapFormatter object.
BinaryFormatter Used to serialize a linked list to a stream in a binary format. The binary formatter
uses a format that only the BinaryFormatter type understands. However, the data is concise.
SoapFormatter Used to serialize a linked list to a stream in the SOAP format. SOAP is a standard
format.
Stream I/O
Stream Used to serialize and deserialize. The specific stream type used in this sample is the
FileStream type. However, serialization can be used with any type derived from Stream.
File Used to create FileStream objects for reading and creating files on disk.
FileStream Used to serialize and deserialize linked lists.
See Also
BinaryFormatter
File
FileStream
IFormatter
SerializableAttribute
SoapFormatter
Stream
System.Runtime.Serialization
System.Xml.Serialization
Random class
System.IO namespace
Basic Serialization
Binary Serialization
Controlling XML Serialization Using Attributes
Introducing XML Serialization
Serialization
XML and SOAP Serialization
Custom Serialization Order With XmlSerializer
4/14/2017 • 1 min to read • Edit Online
Download Sample
This sample shows how to control the order of serialized and deserialized elements for XML serialization.
Review comments in the source code and build.proj files for more information on serialization.
To build the sample using the Command Prompt
1. Open the Command Prompt window and navigate to one of the language-specific subdirectories for the
sample.
2. Type msbuild CustomOrder.sln at the command line.
To build the sample using Visual Studio
1. Open File Explorer and navigate to one of the language-specific subdirectories for the sample.
2. Double-click the icon for the CustomOrder.sln to open the file in Visual Studio.
3. In the Build menu, select Build Solution.
4. The sample application is built in the default \bin or \bin\Debug subdirectory.
See Also
Basic Serialization
Binary Serialization
Controlling XML Serialization Using Attributes
Introducing XML Serialization
Serialization
XML and SOAP Serialization
SchemaImporterExtension Technology Sample
4/14/2017 • 1 min to read • Edit Online
Download Sample
This sample demonstrates a custom SchemaImporterExtension that allows fine control over code generation when
an XML schema is imported. The application shows how to build, register and invoke this extension.
To build the sample using the command prompt
1. Open a Command Prompt window and navigate to one of the language-specific subdirectories for the
sample.
2. Type msbuild.exe OrderSchemaImporterExtension.sln at the command line.
To build the sample using Visual Studio
1. Open File Explorer and navigate to one of the language-specific subdirectories for the sample.
2. Double-click the icon for OrderSchemaImporterExtension.sln to open the file in Visual Studio.
3. On the Build menu, click Build Solution.
The application will be built in the default \bin or \bin\Debug directory.
To run the sample
1. Navigate to the directory containing the new executable, using the command prompt.
2. Type [exe name] at the command line.
Remarks
For more information about sample binary creation and registration steps, see the comments in the source code
and build.proj files.
See Also
CodeCompileUnit
CodeNamespace
CodeNamespaceImport
CSharpCodeProvider
IXmlSerializable
SchemaImporterExtension
System.CodeDom
System.CodeDom.Compiler
System.Web.Services.Description
System.Web.Services.Discovery
System.Xml.Serialization
Uri
VBCodeProvider
WebReference
XmlSchemaImporter
Version Tolerant Serialization Technology Sample
4/14/2017 • 1 min to read • Edit Online
Download Sample
This sample demonstrates the version tolerance features of .NET Serialization. The sample builds applications that
use different versions of a BinaryFormatter to serialize and deserialize data. Despite the presence of different type
versions, the applications communicate seamlessly. For more information, see Version Tolerant Serialization.
To build the sample using the command prompt
1. Open a Command Prompt window and navigate to one of the language-specific subdirectories (under V1
Application or V2 Application) for the sample.
2. Type msbuild.exe <ver> application.sln at the command line (where <ver> is either v1 or v2).
To build the sample using Visual Studio
1. Open File Explorer and navigate to one of the language-specific subdirectories for the sample.
2. Navigate to the V1 Application subdirectory of the directory you selected in the previous step.
3. Double-click the icon for V1 Application.sln to open the file in Visual Studio.
4. On the Build menu, click Build Solution.
5. Navigate to the V2 Application subdirectory and repeat the two previous steps to build the V2 Application.
The applications will be built in the default \bin or \bin\Debug subdirectories of their respective project directories.
To run the sample
1. In the Command Prompt window, navigate to the language-specific subdirectory that you selected when
you built the sample applications.
2. Type runme.cmd at the command line to run both applications at once.
Alternatively, navigate to the directories that contain the new executables and run them sequentially.
NOTE
The sample builds console applications. You must launch and run them in a Command Prompt window to view their output.
See Also
BinaryFormatter
FileStream
Web Services Generics Serialization Technology
Sample
4/14/2017 • 1 min to read • Edit Online
Download Sample
This sample shows how to use and control the serialization of generics in ASP.NET Web Services.
To build the sample using Visual Studio
1. Open Visual Studio and select New Web Site from the File menu.
2. In the New Web Site dialog, select from the left pane your desired programming language, then from the
right pane, select ASP.NET Web Service.
3. Click Browse and navigate to the \CS\GenericsService subdirectory.
4. Select Service.asmx to open the file in Visual Studio.
5. On the Build menu, click Build Solution.
NOTE
The first five steps in this list are optional. The .NET Framework runtime will automatically generate the Web service the first
time the service is requested.
NOTE
The following steps are required to build the sample.
IMPORTANT
Take note of the virtual directory name that is listed in the Aliases pane, because you will need it to run the sample.
Remarks
The sample displays a default ASP.NET page that contains links to the definition of the Web Service. You can
customize the display in addition to modifying the source code for the Web service. For more information, see
Building XML Web Service Clients.
See Also
System.Collections.Generic
System.Web.Services
System.Xml.Serialization
Serialization
XML Web Services Created Using ASP.NET and XML Web Service Clients
Web Services IXmlSerializable Technology Sample
4/14/2017 • 1 min to read • Edit Online
Download Sample
This sample shows how to use IXmlSerializable to control the serialization of custom types in ASP.NET Web
Services.
To build the sample using Visual Studio
1. Open Visual Studio 2005 and select New Web Site from the File menu.
2. In the left pane of the New Web Site dialog, select your desired programming language, then from the
right pane, select ASP.NET Web Service.
3. Type IXmlSerializable as the name of the new Web service.
4. In the Solution Explorer window, right-click the icon for Service.asmx and select Delete; repeat this step for
the Service.asmx codebehind file.
5. Right-click the project directory and select Add Existing Item. In the dialog, navigate to the Service
subdirectory of the language-specific directory.
6. Select Service.asmx, then repeat this step for the Service.asmx codebehind file.
7. Open File Explorer and navigate to the directory that contains IXmlSerializable directory that you created in
step 3 above.
8. Right-click the icon for the IXmlSerializable directory and select Sharing and Security.
9. In the Web Sharing tab, select Share this Folder, and confirm the default settings, including the name
IXmlSerializable.
10. Click OK.
To run the sample
1. Open a browser window and select its address bar.
2. Type http://localhost/IXmlSerializable/Service.asmx.
See Also
IXmlSerializable
System.Xml.Serialization
XmlConvert
XmlQualifiedName
XmlReader
XmlSchema
XmlSchemaSet
XmlUrlResolver
XmlWriter