You are on page 1of 126

Table of Contents

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.

MyObject obj = new MyObject();


obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

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.

IFormatter formatter = new BinaryFormatter();


Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();

// Here's the proof.


Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);

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.

public class MyStuff : MyObject


{
public int n3;
}

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.

Running Custom Methods During and After Serialization


The best practice and easiest way (introduced in version 2.0 of the .NET Framework) is to apply the following
attributes to methods that are used to correct data during and after serialization:
OnDeserializedAttribute
OnDeserializingAttribute
OnSerializedAttribute
OnSerializingAttribute
These attributes allow the type to participate in any one of, or all four of the phases, of the serialization and
deserialization processes. The attributes specify the methods of the type that should be invoked during each phase.
The methods do not access the serialization stream but instead allow you to alter the object before and after
serialization, or before and after deserialization. The attributes can be applied at all levels of the type inheritance
hierarchy, and each method is called in the hierarchy from the base to the most derived. This mechanism avoids
the complexity and any resulting issues of implementing the ISerializable interface by giving the responsibility for
serialization and deserialization to the most derived implementation. Additionally, this mechanism allows the
formatters to ignore the population of fields and retrieval from the serialization stream. For details and examples of
controlling serialization and deserialization, click any of the previous links.
In addition, when adding a new field to an existing serializable type, apply the OptionalFieldAttribute attribute to
the field. The BinaryFormatter and the SoapFormatter ignores the absence of the field when a stream that is
missing the new field is processed.

Implementing the ISerializable Interface


The other way to control serialization is achieved by implementing the ISerializable interface on an object. Note,
however, that the method in the previous section supersedes this method to control serialization.
In addition, you should not use default serialization on a class that is marked with the Serializable attribute and
has declarative or imperative security at the class level or on its constructors. Instead, these classes should always
implement the ISerializable interface.
Implementing ISerializable involves implementing the GetObjectData method and a special constructor that is
used when the object is deserialized. The following sample code shows how to implement ISerializable on the
MyObject class from a previous section.

[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;

public MyObject()
{
}

protected MyObject(SerializationInfo info, StreamingContext context)


{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter =true)]

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)


{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}

<Serializable()> _
Public Class MyObject
Implements ISerializable
Public n1 As Integer
Public n2 As Integer
Public str As String

Public Sub New()


End Sub

Protected Sub New(ByVal info As SerializationInfo, _


ByVal context As StreamingContext)
n1 = info.GetInt32("i")
n2 = info.GetInt32("j")
str = info.GetString("k")
End Sub 'New

<SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter := True)> _


Public Overridable Sub GetObjectData(ByVal info As _
SerializationInfo, ByVal context As StreamingContext)
info.AddValue("i", n1)
info.AddValue("j", n2)
info.AddValue("k", str)
End Sub
End Class

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;

public ObjectTwo() : base()


{
}

protected ObjectTwo(SerializationInfo si,


StreamingContext context) : base(si,context)
{
num = si.GetInt32("num");
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo si,
StreamingContext context)
{
base.GetObjectData(si,context);
si.AddValue("num", num);
}
}

<Serializable()> _
Public Class ObjectTwo
Inherits MyObject
Public num As Integer

Public Sub New()

End Sub

Protected Sub New(ByVal si As SerializationInfo, _


ByVal context As StreamingContext)
MyBase.New(si, context)
num = si.GetInt32("num")
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.

Tolerance of Extraneous or Unexpected Data


In the past, during deserialization, any extraneous or unexpected data caused exceptions to be thrown. With VTS, in
the same situation, any extraneous or unexpected data is ignored instead of causing exceptions to be thrown. This
enables applications that use newer versions of a type (that is, a version that includes more fields) to send
information to applications that expect older versions of the same type.
In the following example, the extra data contained in the CountryField of version 2.0 of the Address class is
ignored when an older application deserializes the newer version.
// Version 1 of the Address class.
[Serializable]
public class Address
{
public string Street;
public string City;
}
// Version 2.0 of the Address class.
[Serializable]
public class Address
{
public string Street;
public string City;
// The older application ignores this data.
public string CountryField;
}

' Version 1 of the Address class.


<Serializable> _
Public Class Address
Public Street As String
Public City As String
End Class

' Version 2.0 of the Address class.


<Serializable> _
Public Class Address
Public Street As String
Public City As String
' The older application ignores this data.
Public CountryField As String
End Class

Tolerance of Missing Data


Fields can be marked as optional by applying the OptionalFieldAttribute attribute to them. During deserialization, if
the optional data is missing, the serialization engine ignores the absence and does not throw an exception. Thus,
applications that expect older versions of a type can send data to applications that expect newer versions of the
same type.
The following example shows version 2.0 of the Address class with the CountryField field marked as optional. If
an older application sends version 1 to a newer application that expects version 2.0, the absence of the data is
ignored.

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

WHEN THE ASSOCIATED METHOD IS


ATTRIBUTE CALLED TYPICAL USE

OnDeserializingAttribute Before deserialization.* Initialize default values for optional


fields.

OnDeserializedAttribute After deserialization. Fix optional field values based on


contents of other fields.

OnSerializingAttribute Before serialization. Prepare for serialization. For example,


create optional data structures.

OnSerializedAttribute After serialization. Log serialization events.

* This callback is invoked before the deserialization constructor, if one is present.


Using Callbacks
To use callbacks, apply the appropriate attribute to a method that accepts a StreamingContext parameter. Only one
method per class can be marked with each of these attributes. For example:

[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

The VersionAdded Property


The OptionalFieldAttribute has the VersionAdded property. In version 2.0 of the .NET Framework, this is not
used. However, it is important to set this property correctly to ensure that the type will be compatible with future
serialization engines.
The property indicates which version of a type a given field has been added. It should be incremented by exactly
one (starting at 2) every time the type is modified, as shown in the following example:
// Version 1.0
[Serializable]
public class Person
{
public string FullName;
}

// 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;
}

' Version 1.0


<Serializable> _
Public Class Person
Public FullName
End Class

' Version 2.0


<Serializable> _
Public Class Person
Public FullName As String

<OptionalField(VersionAdded := 2)> _
Public NickName As String
<OptionalField(VersionAdded := 2)> _
Public BirthDate As DateTime
End Class

' Version 3.0


<Serializable> _
Public Class Person
Public FullName As String

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

TECHNOLOGY RELEVANT CLASSES NOTES

Data Contract Serialization DataContractAttribute General persistence

DataMemberAttribute Web Services

DataContractSerializer JSON

NetDataContractSerializer

DataContractJsonSerializer

ISerializable

XML Serialization XmlSerializer XML format


with full control

Runtime -Serialization (Binary and SerializableAttribute .NET Remoting


SOAP)
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; }

public Person(string firstNameValue, string lastNameValue)


{
FirstName = firstNameValue;
LastName = lastNameValue;
}
}

<DataContract()> Public Class Person


<DataMember()> Public Property LastName As String
<DataMember()> Public Property FirstName As String

Public Sub New(ByVal firstNameValue As String, ByVal lastNameValue As String)


FirstName = firstNameValue
LastName = lastNameValue
End Sub

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;

public Person2(string firstName, string lastName)


{
this.lastName = lastName;
this.firstName = 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; }
}
}

<DataContract()> Class Person2


Private lastNameValue As String
Private firstNameValue As String

Public Sub New(ByVal firstName As String, ByVal lastName As String)


Me.lastNameValue = lastName
Me.firstNameValue = firstName
End Sub

<DataMember()> Property LastName As String


Get
Return lastNameValue
End Get

Set(ByVal value As String)


lastNameValue = value
End Set

End Property

<DataMember()> Property FirstName As String


Get
Return firstNameValue

End Get
Set(ByVal value As String)
firstNameValue = value
End Set
End Property

End Class

3. CONSIDER using the serialization callbacks for initialization of deserialized instances.


Constructors are not called when objects are deserialized. Therefore, any logic that executes during normal
construction needs to be implemented as one of the serialization callbacks.

[DataContract]
class Person3
{
[DataMember]
string lastName;
[DataMember]
string firstName;
string fullName;

public Person3(string firstName, string lastName)


{
// This constructor is not called during deserialization.
this.lastName = lastName;
this.firstName = firstName;
fullName = firstName + " " + lastName;
}

public string FullName


{
get { return fullName; }
}

// This method is called after the object


// is completely deserialized. Use it instead of the
// constructror.
[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
fullName = firstName + " " + lastName;
}
}

<DataContract()> _
Class Person3
<DataMember()> Private lastNameValue As String
<DataMember()> Private firstNameValue As String
Dim fullNameValue As String

Public Sub New(ByVal firstName As String, ByVal lastName As String)


lastNameValue = lastName
firstNameValue = firstName
fullNameValue = firstName & " " & lastName
End Sub

Public ReadOnly Property FullName As String


Get
Return fullNameValue
End Get
End Property

<OnDeserialized()> Sub OnDeserialized(ByVal context As StreamingContext)


fullNameValue = firstNameValue & " " & lastNameValue
End Sub
End Class

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.

// The KnownTypeAttribute specifies types to be


// used during serialization.
[KnownType(typeof(USAddress))]
[DataContract]
class Person4
{

[DataMember]
string fullNameValue;
[DataMember]
Address address; // Address is abstract

public Person4(string fullName, Address address)


{
this.fullNameValue = fullName;
this.address = address;
}

public string FullName


{
get { return fullNameValue; }
}
}

[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; }

public override string FullAddress


{
get
{
return Street + "\n" + City + ", " + State + " " + ZipCode;
}
}
}
<KnownType(GetType(USAddress)), _
DataContract()> Class Person4
<DataMember()> Property fullNameValue As String
<DataMember()> Property addressValue As USAddress ' Address is abstract

Public Sub New(ByVal fullName As String, ByVal address As Address)


fullNameValue = fullName
addressValue = address
End Sub

Public ReadOnly Property FullName() As String


Get
Return fullNameValue
End Get

End Property
End Class

<DataContract()> Public MustInherit Class Address


Public MustOverride Function FullAddress() As String
End Class

<DataContract()> Public Class USAddress


Inherits Address
<DataMember()> Public Property Street As String
<DataMember()> Public City As String
<DataMember()> Public State As String
<DataMember()> Public ZipCode As String

Public Overrides Function FullAddress() As String


Return Street & "\n" & City & ", " & State & " " & ZipCode
End Function
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;

public Person5(string fullName)


{
this.fullNameValue = fullName;
}

public string FullName


{
get { return fullNameValue; }
}

ExtensionDataObject IExtensibleDataObject.ExtensionData
{
get
{
return serializationData;
}
set { serializationData = value; }
}
}

<DataContract()> Class Person5


Implements IExtensibleDataObject
<DataMember()> Dim fullNameValue As String

Public Sub New(ByVal fullName As String)


fullName = fullName
End Sub

Public ReadOnly Property FullName


Get
Return fullNameValue
End Get
End Property
Private serializationData As ExtensionDataObject
Public Property ExtensionData As ExtensionDataObject Implements IExtensibleDataObject.ExtensionData
Get
Return serializationData
End Get
Set(ByVal value As ExtensionDataObject)
serializationData = value
End Set
End Property
End Class

For more information, see Forward-Compatible Data Contracts.


Supporting XML Serialization
Data contract serialization is the main (default) serialization technology in the .NET Framework, but there are
serialization scenarios that data contract serialization does not support. For example, it does not give you full
control over the shape of XML produced or consumed by the serializer. If such fine control is required, XML
serialization has to be used, and you need to design your types to support this serialization technology.
1. AVOID designing your types specifically for XML Serialization, unless you have a very strong reason to
control the shape of the XML produced. This serialization technology has been superseded by the Data
Contract Serialization discussed in the previous section.
In other words, don’t apply attributes from the System.Runtime.Serialization namespace to new types,
unless you know that the type will be used with XML Serialization. The following example shows how
System.Xml.Serialization can be used to control the shape of the XML -produced.

public class Address2


{
[System.Xml.Serialization.XmlAttribute] // Serialize as XML attribute, instead of an element.
public string Name { get { return "Poe, Toni"; } set { } }
[System.Xml.Serialization.XmlElement(ElementName = "StreetLine")] // Explicitly name the element.
public string Street = "1 Main Street";
}

Public Class Address2


' Supports XML Serialization.
<System.Xml.Serialization.XmlAttribute()> _
Public ReadOnly Property Name As String ' Serialize as XML attribute, instead of an element.
Get
Return "Poe, Toni"
End Get
End Property
<System.Xml.Serialization.XmlElement(ElementName:="StreetLine")> _
Public Street As String = "1 Main Street" ' Explicitly names the element 'StreetLine'.
End Class

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.

// Apply SerializableAttribute to support runtime serialization.


[Serializable]
public class Person6
{
// Code not shown.
}

<Serializable()> Public Class Person6 ' Support runtime serialization with the SerializableAttribute.

' Code not shown.


End Class

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.

// Implement the ISerializable interface for more control.


[Serializable]
public class Person_Runtime_Serializable : ISerializable
{
string fullName;

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);
}

public string FullName


{
get { return fullName; }
set { fullName = value; }
}
}
' Implement the ISerializable interface for more control.
<Serializable()> Public Class Person_Runtime_Serializable
Implements ISerializable

Private fullNameValue As String

Public Sub New()


' empty constructor.
End Sub
Protected Sub New(ByVal info As SerializationInfo, _
ByVal context As StreamingContext)
If info Is Nothing Then
Throw New System.ArgumentNullException("info")
FullName = CType(info.GetValue("name", GetType(String)), String)
End If
End Sub

Private Sub GetObjectData(ByVal info As SerializationInfo, _


ByVal context As StreamingContext) _
Implements ISerializable.GetObjectData
If info Is Nothing Then
Throw New System.ArgumentNullException("info")
info.AddValue("name", FullName)
End If
End Sub

Public Property FullName As String

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.

protected Person_Runtime_Serializable(SerializationInfo info, StreamingContext context){

Protected Sub New(ByVal info As SerializationInfo, _


ByVal context As StreamingContext)

4. DO implement the ISerializable members explicitly.

void ISerializable.GetObjectData(SerializationInfo info,


StreamingContext context) {

Private Sub GetObjectData(ByVal info As SerializationInfo, _


ByVal context As StreamingContext) _
Implements ISerializable.GetObjectData

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

<Serializable()> Public Class Person_Runtime_Serializable2


Implements ISerializable
<SecurityPermission(SecurityAction.LinkDemand,
Flags:=SecurityPermissionFlag.SerializationFormatter)> _
Private Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, _
ByVal context As System.Runtime.Serialization.StreamingContext) _
Implements System.Runtime.Serialization.ISerializable.GetObjectData
' Code not shown.
End Sub
End Class

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

// Turn off response buffering.


System.Web.HttpContext.Current.Response.Buffer = false;
// Return a song.
SongStream song = new SongStream(filePath);
return song;
}
<WebMethod(), System.Web.Services.Protocols.SoapDocumentMethodAttribute(ParameterStyle :=
SoapParameterStyle.Bare)> _
Public Function DownloadSong(ByVal Authorization As DownloadAuthorization, ByVal filePath As String) As
SongStream

' Turn off response buffering.


System.Web.HttpContext.Current.Response.Buffer = False
' Return a song.
Dim song As New SongStream(filePath)
Return song

End Function
End Class 'Test

[XmlSchemaProvider("MySchema")]
public class SongStream : IXmlSerializable
{

private const string ns = "http://demos.Contoso.com/webservices";


private string filePath;

public SongStream(){ }

public SongStream(string filePath)


{
this.filePath = filePath;
}

// This is the method named by the XmlSchemaProviderAttribute applied to the type.


public static XmlQualifiedName MySchema(XmlSchemaSet xs)
{
// This method is called by the framework to get the schema for this type.
// We return an existing schema from disk.

XmlSerializer schemaSerializer = new XmlSerializer(typeof(XmlSchema));


string xsdPath = null;
// NOTE: replace the string with your own path.
xsdPath = System.Web.HttpContext.Current.Server.MapPath("SongStream.xsd");
XmlSchema s = (XmlSchema)schemaSerializer.Deserialize(
new XmlTextReader(xsdPath), null);
xs.XmlResolver = new XmlUrlResolver();
xs.Add(s);

return new XmlQualifiedName("songStream", ns);


}

void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)


{
// This is the chunking code.
// ASP.NET buffering must be turned off for this to work.

int bufferSize = 4096;


char[] songBytes = new char[bufferSize];
FileStream inFile = File.Open(this.filePath, FileMode.Open, FileAccess.Read);

long length = inFile.Length;

// Write the file name.


writer.WriteElementString("fileName", ns, Path.GetFileNameWithoutExtension(this.filePath));

// Write the size.


writer.WriteElementString("size", ns, length.ToString());

// Write the song bytes.


writer.WriteStartElement("song", ns);

StreamReader sr = new StreamReader(inFile, true);


int readLen = sr.Read(songBytes, 0, bufferSize);

while (readLen > 0)


{
writer.WriteStartElement("chunk", ns);
writer.WriteChars(songBytes, 0, readLen);
writer.WriteEndElement();

writer.Flush();
readLen = sr.Read(songBytes, 0, bufferSize);
}

writer.WriteEndElement();
inFile.Close();

System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new System.NotImplementedException();
}

void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)


{
throw new System.NotImplementedException();

}
}

<XmlSchemaProvider("MySchema")> _
Public Class SongStream
Implements IXmlSerializable

Private Const ns As String = "http://demos.Contoso.com/webservices"


Private filePath As String

Public Sub New()

End Sub

Public Sub New(ByVal filePath As String)


Me.filePath = filePath
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)

Return New XmlQualifiedName("songStream", ns)

End Function

Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml


Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml
' This is the chunking code.
' ASP.NET buffering must be turned off for this to work.

Dim bufferSize As Integer = 4096


Dim songBytes(bufferSize) As Char
Dim inFile As FileStream = File.Open(Me.filePath, FileMode.Open, FileAccess.Read)

Dim length As Long = inFile.Length

' Write the file name.


writer.WriteElementString("fileName", ns, Path.GetFileNameWithoutExtension(Me.filePath))

' Write the size.


writer.WriteElementString("size", ns, length.ToString())

' Write the song bytes.


writer.WriteStartElement("song", ns)

Dim sr As New StreamReader(inFile, True)


Dim readLen As Integer = sr.Read(songBytes, 0, bufferSize)

While readLen > 0


writer.WriteStartElement("chunk", ns)
writer.WriteChars(songBytes, 0, readLen)
writer.WriteEndElement()

writer.Flush()
readLen = sr.Read(songBytes, 0, bufferSize)
End While

writer.WriteEndElement()
inFile.Close()
End Sub

Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema


Throw New System.NotImplementedException()
End Function

Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml


Throw New System.NotImplementedException()
End Sub
End Class

public class SongFile : IXmlSerializable


{
public static event ProgressMade OnProgress;

public SongFile()
{ }

private const string ns = "http://demos.teched2004.com/webservices";


public static string MusicPath;
private string filePath;
private double size;

void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)


{
reader.ReadStartElement("DownloadSongResult", ns);
ReadFileName(reader);
ReadSongSize(reader);
ReadAndSaveSong(reader);
reader.ReadEndElement();
}

void ReadFileName(XmlReader reader)


{
{
string fileName = reader.ReadElementString("fileName", ns);
this.filePath =
Path.Combine(MusicPath, Path.ChangeExtension(fileName, ".mp3"));
}

void ReadSongSize(XmlReader reader)


{
this.size = Convert.ToDouble(reader.ReadElementString("size", ns));
}

void ReadAndSaveSong(XmlReader reader)


{
FileStream outFile = File.Open(
this.filePath, FileMode.Create, FileAccess.Write);

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();
}

public void WriteXml(XmlWriter writer)


{
throw new System.NotImplementedException();
}
}

Public Class SongFile


Implements IXmlSerializable
Public Shared Event OnProgress As ProgressMade
Public Sub New()

End Sub

Private Const ns As String = "http://demos.teched2004.com/webservices"


Public Shared MusicPath As String
Private filePath As String
Private size As Double

Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml


reader.ReadStartElement("DownloadSongResult", ns)
ReadFileName(reader)
ReadSongSize(reader)
ReadAndSaveSong(reader)
reader.ReadEndElement()
End Sub

Sub ReadFileName(ByVal reader As XmlReader)


Dim fileName As String = reader.ReadElementString("fileName", ns)
Me.filePath = Path.Combine(MusicPath, Path.ChangeExtension(fileName, ".mp3"))

End Sub

Sub ReadSongSize(ByVal reader As XmlReader)


Me.size = Convert.ToDouble(reader.ReadElementString("size", ns))

End Sub

Sub ReadAndSaveSong(ByVal reader As XmlReader)


Dim outFile As FileStream = File.Open(Me.filePath, FileMode.Create, FileAccess.Write)

Dim songBase64 As String


Dim songBytes() As Byte
reader.ReadStartElement("song", ns)
Dim totalRead As Double = 0
While True
If reader.IsStartElement("chunk", ns) Then
songBase64 = reader.ReadElementString()
totalRead += songBase64.Length
songBytes = Convert.FromBase64String(songBase64)
outFile.Write(songBytes, 0, songBytes.Length)
outFile.Flush()
RaiseEvent OnProgress((100 *(totalRead / size)))
Else
Exit While
End If
End While

outFile.Close()
reader.ReadEndElement()
End Sub

<PermissionSet(SecurityAction.Demand, Name :="FullTrust")> _


Public Sub Play()
System.Diagnostics.Process.Start(Me.filePath)
End Sub

Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema


Throw New System.NotImplementedException()
End Function

Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml


Throw New System.NotImplementedException()
End Sub
End Class
Compiling the Code
The code uses the following namespaces: System, System.Runtime.Serialization, System.Web.Services,
System.Web.Services.Protocols, System.Xml, System.Xml.Serialization, and System.Xml.Schema.

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

Public Class Book


public ISBN As String
End Class

Public Class ExpandedBook


Inherits Book
public NewEdition As Boolean
End Class

Public Class Run


Shared Sub Main()
Dim t As Run = New Run()
t.SerializeObject("Book.xml")
t.DeserializeObject("Book.xml")
End Sub

Public Sub SerializeObject(filename As String)


' Each overridden field, property, or type requires
' an XmlAttributes instance.
Dim attrs As XmlAttributes = New XmlAttributes()

' Creates an XmlElementAttribute instance to override the


' field that returns Book objects. The overridden field
' returns Expanded objects instead.
Dim attr As XmlElementAttribute = _
New XmlElementAttribute()
attr.ElementName = "NewBook"
attr.Type = GetType(ExpandedBook)

' Adds the element to the collection of elements.


attrs.XmlElements.Add(attr)

' Creates the XmlAttributeOverrides.


Dim attrOverrides As XmlAttributeOverrides = _
New XmlAttributeOverrides()

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

' Creates the XmlSerializer using the XmlAttributeOverrides.


Dim s As XmlSerializer = _
New XmlSerializer(GetType(Orders), attrOverrides)

' Writing the file requires a TextWriter instance.


Dim writer As TextWriter = New StreamWriter(filename)

' Creates the object to be serialized.


Dim myOrders As Orders = New Orders()

' Creates an object of the derived type.


Dim b As ExpandedBook = New ExpandedBook()
b.ISBN= "123456789"
b.NewEdition = True
myOrders.Books = New ExpandedBook(){b}

' Serializes the object.


s.Serialize(writer,myOrders)
writer.Close()
End Sub

Public Sub DeserializeObject(filename As String)


Dim attrOverrides As XmlAttributeOverrides = _
New XmlAttributeOverrides()
Dim attrs As XmlAttributes = New XmlAttributes()

' Creates an XmlElementAttribute to override the


' field that returns Book objects. The overridden field
' returns Expanded objects instead.
Dim attr As XmlElementAttribute = _
New XmlElementAttribute()
attr.ElementName = "NewBook"
attr.Type = GetType(ExpandedBook)

' Adds the XmlElementAttribute to the collection of objects.


attrs.XmlElements.Add(attr)

attrOverrides.Add(GetType(Orders), "Books", attrs)

' Creates the XmlSerializer using the XmlAttributeOverrides.


Dim s As XmlSerializer = _
New XmlSerializer(GetType(Orders), attrOverrides)

Dim fs As FileStream = New FileStream(filename, FileMode.Open)


Dim myOrders As Orders = CType( s.Deserialize(fs), Orders)
Console.WriteLine("ExpandedBook:")

' The difference between deserializing the overridden


' XML document and serializing it is this: To read the derived
' object values, you must declare an object of the derived type
' and cast the returned object to it.
Dim expanded As ExpandedBook
Dim b As Book
for each b in myOrders.Books
expanded = CType(b, ExpandedBook)
Console.WriteLine(expanded.ISBN)
Console.WriteLine(expanded.NewEdition)
Next
End Sub
End Class

public class Orders


{
public Book[] Books;
}
public class Book
{
public string ISBN;
}

public class ExpandedBook:Book


{
public bool NewEdition;
}

public class Run


{
public void SerializeObject(string filename)
{
// Each overridden field, property, or type requires
// an XmlAttributes instance.
XmlAttributes attrs = new XmlAttributes();

// Creates an XmlElementAttribute instance to override the


// field that returns Book objects. The overridden field
// returns Expanded objects instead.
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "NewBook";
attr.Type = typeof(ExpandedBook);

// Adds the element to the collection of elements.


attrs.XmlElements.Add(attr);

// Creates the XmlAttributeOverrides instance.


XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

// Adds the type of the class that contains the overridden


// member, as well as the XmlAttributes instance to override it
// with, to the XmlAttributeOverrides.
attrOverrides.Add(typeof(Orders), "Books", attrs);

// Creates the XmlSerializer using the XmlAttributeOverrides.


XmlSerializer s =
new XmlSerializer(typeof(Orders), attrOverrides);

// Writing the file requires a TextWriter instance.


TextWriter writer = new StreamWriter(filename);

// Creates the object to be serialized.


Orders myOrders = new Orders();

// Creates an object of the derived type.


ExpandedBook b = new ExpandedBook();
b.ISBN= "123456789";
b.NewEdition = true;
myOrders.Books = new ExpandedBook[]{b};

// Serializes the object.


s.Serialize(writer,myOrders);
writer.Close();
}

public void DeserializeObject(string filename)


{
XmlAttributeOverrides attrOverrides =
new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();

// Creates an XmlElementAttribute to override the


// field that returns Book objects. The overridden field
// returns Expanded objects instead.
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "NewBook";
attr.ElementName = "NewBook";
attr.Type = typeof(ExpandedBook);

// Adds the XmlElementAttribute to the collection of objects.


attrs.XmlElements.Add(attr);

attrOverrides.Add(typeof(Orders), "Books", attrs);

// Creates the XmlSerializer using the XmlAttributeOverrides.


XmlSerializer s =
new XmlSerializer(typeof(Orders), attrOverrides);

FileStream fs = new FileStream(filename, FileMode.Open);


Orders myOrders = (Orders) s.Deserialize(fs);
Console.WriteLine("ExpandedBook:");

// The difference between deserializing the overridden


// XML document and serializing it is this: To read the derived
// object values, you must declare an object of the derived type
// and cast the returned object to it.
ExpandedBook expanded;
foreach(Book b in myOrders.Books)
{
expanded = (ExpandedBook)b;
Console.WriteLine(
expanded.ISBN + "\n" +
expanded.NewEdition);
}
}
}

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.

Security Considerations for XmlSerializer Applications


When creating an application that uses the XmlSerializer, you should be aware of the following items and their
implications:
The XmlSerializer creates C# (.cs) files and compiles them into .dll files in the directory named by the
TEMP environment variable; serialization occurs with those DLLs.

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.

Serialization of a Simple Class


The following code example shows a basic class with a public field.

Public Class OrderForm


Public OrderDate As DateTime
End Class

public class OrderForm


{
public DateTime OrderDate;
}

When an instance of this class is serialized, it might resemble the following.

<OrderForm>
<OrderDate>12/12/01</OrderDate>
</OrderForm>

For more examples of serialization, see Examples of XML Serialization.

Items That Can Be Serialized


The following items can be serialized using the XmLSerializer class:
Public read/write properties and fields of public classes.
Classes that implement ICollection or IEnumerable.

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.

Advantages of Using XML Serialization


The XmlSerializerclass gives you complete and flexible control when you serialize an object as XML. If you are
creating an XML Web service, you can apply attributes that control serialization to classes and members to ensure
that the XML output conforms to a specific schema.
For example, XmlSerializer enables you to:
Specify whether a field or property should be encoded as an attribute or an element.
Specify an XML namespace to use.
Specify the name of an element or attribute if a field or property name is inappropriate.
Another advantage of XML serialization is that you have no constraints on the applications you develop, as long
as the XML stream that is generated conforms to a given schema. Imagine a schema that is used to describe
books. It features a title, author, publisher, and ISBN number element. You can develop an application that
processes the XML data in any way you want, for example, as a book order, or as an inventory of books. In either
case, the only requirement is that the XML stream conforms to the specified XML Schema definition language
(XSD) schema.

XML Serialization Considerations


The following should be considered when using the XmlSerializer class:
The Sgen.exe tool is expressly designed to generate serialization assemblies for optimum performance.
The serialized data contains only the data itself and the structure of your classes. Type identity and
assembly information are not included.
Only public properties and fields can be serialized. Properties must have public accessors (get and set
methods). If you must serialize non-public data, use the DataContractSerializer class rather than XML
serialization.
A class must have a default constructor to be serialized by XmlSerializer.
Methods cannot be serialized.
XmlSerializer can process classes that implement IEnumerable or ICollection differently if they meet
certain requirements, as follows.
A class that implements IEnumerable must implement a public Add method that takes a single
parameter. The Add method's parameter must be consistent (polymorphic) with the type returned from
the IEnumerator.Current property returned from the GetEnumerator method.
A class that implements ICollection in addition to IEnumerable (such as CollectionBase) must have a
public Item indexed property (an indexer in C#) that takes an integer and it must have a public Count
property of type integer. The parameter passed to the Add method must be the same type as that
returned from the Item property, or one of that type's bases.
For classes that implement ICollection, values to be serialized are retrieved from the indexed Item
property rather than by calling GetEnumerator. Also, public fields and properties are not serialized, with
the exception of public fields that return another collection class (one that implements ICollection). For an
example, see Examples of XML Serialization.

XSD Data Type Mapping


The World Wide Web Consortium (www.w3.org) document titled "XML Schema Part 2: Datatypes" specifies the
simple data types that are allowed in an XML Schema definition language (XSD) schema. For many of these (for
example, int and decimal), there is a corresponding data type in the .NET Framework. However, some XML data
types do not have a corresponding data type in the .NET Framework (for example, the NMTOKEN data type). In
such cases, if you use the XML Schema Definition tool (XML Schema Definition Tool (Xsd.exe)) to generate classes
from a schema, an appropriate attribute is applied to a member of type string, and its DataType property is set to
the XML data type name. For example, if a schema contains an element named "MyToken" with the XML data type
NMTOKEN, the generated class might contain a member as shown in the following example.

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

Dim myObject As MySerializableClass


' Construct an instance of the XmlSerializer with the type
' of object that is being deserialized.
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass))
' To read the file, create a FileStream.
Dim myFileStream As FileStream = _
New FileStream("myFileName.xml", FileMode.Open)
' Call the Deserialize method and cast to the object type.
myObject = CType( _
mySerializer.Deserialize(myFileStream), MySerializableClass)

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.

Private Sub SerializeDataSet(filename As String)


Dim ser As XmlSerializer = new XmlSerializer(GetType(DataSet))
' Creates a DataSet; adds a table, column, and ten rows.
Dim ds As DataSet = new DataSet("myDataSet")
Dim t As DataTable = new DataTable("table1")
Dim c As DataColumn = new DataColumn("thing")
t.Columns.Add(c)
ds.Tables.Add(t)
Dim r As DataRow
Dim i As Integer
for i = 0 to 10
r = t.NewRow()
r(0) = "Thing " & i
t.Rows.Add(r)
Next
Dim writer As TextWriter = new StreamWriter(filename)
ser.Serialize(writer, ds)
writer.Close()
End Sub

private void SerializeDataSet(string filename){


XmlSerializer ser = new XmlSerializer(typeof(DataSet));

// Creates a DataSet; adds a table, column, and ten rows.


DataSet ds = new DataSet("myDataSet");
DataTable t = new DataTable("table1");
DataColumn c = new DataColumn("thing");
t.Columns.Add(c);
ds.Tables.Add(t);
DataRow r;
for(int i = 0; i<10;i++){
r = t.NewRow();
r[0] = "Thing " + i;
t.Rows.Add(r);
}
TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, ds);
writer.Close();
}

Serializing an XmlElement and XmlNode


You can also serialize instances of a XmlElement or XmlNode class, as shown in the following code example.
private Sub SerializeElement(filename As String)
Dim ser As XmlSerializer = new XmlSerializer(GetType(XmlElement))
Dim myElement As XmlElement = _
new XmlDocument().CreateElement("MyElement", "ns")
myElement.InnerText = "Hello World"
Dim writer As TextWriter = new StreamWriter(filename)
ser.Serialize(writer, myElement)
writer.Close()
End Sub

Private Sub SerializeNode(filename As String)


Dim ser As XmlSerializer = _
new XmlSerializer(GetType(XmlNode))
Dim myNode As XmlNode = new XmlDocument(). _
CreateNode(XmlNodeType.Element, "MyNode", "ns")
myNode.InnerText = "Hello Node"
Dim writer As TextWriter = new StreamWriter(filename)
ser.Serialize(writer, myNode)
writer.Close()
End Sub

private void SerializeElement(string filename){


XmlSerializer ser = new XmlSerializer(typeof(XmlElement));
XmlElement myElement=
new XmlDocument().CreateElement("MyElement", "ns");
myElement.InnerText = "Hello World";
TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, myElement);
writer.Close();
}

private void SerializeNode(string filename){


XmlSerializer ser = new XmlSerializer(typeof(XmlNode));
XmlNode myNode= new XmlDocument().
CreateNode(XmlNodeType.Element, "MyNode", "ns");
myNode.InnerText = "Hello Node";
TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, myNode);
writer.Close();
}

Serializing a Class that Contains a Field Returning a Complex Object


If a property or field returns a complex object (such as an array or a class instance), the XmlSerializer converts it to
an element nested within the main XML document. For example, the first class in the following code example
returns an instance of the second class.

Public Class PurchaseOrder


Public MyAdress As Address
End Class

Public Class Address


Public FirstName As String
End Class
public class PurchaseOrder
{
public Address MyAddress;
}
public class Address
{
public string FirstName;
}

The serialized XML output might resemble the following.

<PurchaseOrder>
<Address>
<FirstName>George</FirstName>
</Address>
</PurchaseOrder>

Serializing an Array of Objects


You can also serialize a field that returns an array of objects, as shown in the following code example.

Public Class PurchaseOrder


public ItemsOrders () As Item
End Class

Public Class Item


Public ItemID As String
Public ItemPrice As decimal
End Class

public class PurchaseOrder


{
public Item [] ItemsOrders
}

public class Item


{
public string ItemID
public decimal ItemPrice
}

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

Public Class Test


Shared Sub Main()
Dim t As Test= new Test()
t.SerializeCollection("coll.xml")
End Sub

Private Sub SerializeCollection(filename As String)


Dim Emps As Employees = new Employees()
' Note that only the collection is serialized -- not the
' CollectionName or any other public property of the class.
Emps.CollectionName = "Employees"
Dim John100 As Employee = new Employee("John", "100xxx")
Emps.Add(John100)
Dim x As XmlSerializer = new XmlSerializer(GetType(Employees))
Dim writer As TextWriter = new StreamWriter(filename)
x.Serialize(writer, Emps)
writer.Close()
End Sub
End Class

Public Class Employees


Implements ICollection
Public CollectionName As String
Private empArray As ArrayList = new ArrayList()

Public ReadOnly Default Overloads _


Property Item(index As Integer) As Employee
get
return CType (empArray(index), Employee)
End Get
End Property

Public Sub CopyTo(a As Array, index As Integer) _


Implements ICollection.CopyTo
empArray.CopyTo(a, index)
End Sub

Public ReadOnly Property Count () As integer Implements _


ICollection.Count
get
Count = empArray.Count
End Get

End Property

Public ReadOnly Property SyncRoot ()As Object _


Implements ICollection.SyncRoot
get
return me
End Get
End Property

Public ReadOnly Property IsSynchronized () As Boolean _


Implements ICollection.IsSynchronized
get
get
return false
End Get
End Property

Public Function GetEnumerator() As IEnumerator _


Implements IEnumerable.GetEnumerator

return empArray.GetEnumerator()
End Function

Public Function Add(newEmployee As Employee) As Integer


empArray.Add(newEmployee)
return empArray.Count
End Function
End Class

Public Class Employee


Public EmpName As String
Public EmpID As String

Public Sub New ()


End Sub

Public Sub New (newName As String , newID As String )


EmpName = newName
EmpID = newID
End Sub
End Class
using System;
using System.IO;
using System.Collections;
using System.Xml.Serialization;

public class Test{


static void Main(){
Test t = new Test();
t.SerializeCollection("coll.xml");
}

private void SerializeCollection(string filename){


Employees Emps = new Employees();
// Note that only the collection is serialized -- not the
// CollectionName or any other public property of the class.
Emps.CollectionName = "Employees";
Employee John100 = new Employee("John", "100xxx");
Emps.Add(John100);
XmlSerializer x = new XmlSerializer(typeof(Employees));
TextWriter writer = new StreamWriter(filename);
x.Serialize(writer, Emps);
}
}
public class Employees:ICollection{
public string CollectionName;
private ArrayList empArray = new ArrayList();

public Employee this[int index]{


get{return (Employee) empArray[index];}
}

public void CopyTo(Array a, int index){


empArray.CopyTo(a, index);
}
public int Count{
get{return empArray.Count;}
}
public object SyncRoot{
get{return this;}
}
public bool IsSynchronized{
get{return false;}
}
public IEnumerator GetEnumerator(){
return empArray.GetEnumerator();
}

public void Add(Employee newEmployee){


empArray.Add(newEmployee);
}
}

public class Employee{


public string EmpName;
public string EmpID;
public Employee(){}
public Employee(string empName, string empID){
EmpName = empName;
EmpID = empID;
}
}

Purchase Order Example


You can cut and paste the following example code into a text file renamed with a .cs or .vb file name extension.
Use the C# or Visual Basic compiler to compile the file. Then run it using the name of the executable.
This example uses a simple scenario to demonstrate how an instance of an object is created and serialized into a
file stream using the Serialize method. The XML stream is saved to a file, and the same file is then read back and
reconstructed into a copy of the original object using the Deserialize method.
In this example, a class named PurchaseOrder is serialized and then deserialized. A second class named Address
is also included because the public field named ShipTo must be set to an Address . Similarly, an OrderedItem
class is included because an array of OrderedItem objects must be set to the OrderedItems field. Finally, a class
named Test contains the code that serializes and deserializes the classes.
The CreatePO method creates the PurchaseOrder , Address , and OrderedItem class objects, and sets the public
field values. The method also constructs an instance of the XmlSerializer class that is used to serialize and
deserialize the PurchaseOrder . Note that the code passes the type of the class that will be serialized to the
constructor. The code also creates a FileStream that is used to write the XML stream to an XML document.
The ReadPo method is a little simpler. It just creates objects to deserialize and reads out their values. As with the
CreatePo method, you must first construct a XmlSerializer, passing the type of the class to be deserialized to the
constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the
Deserialize method with the FileStream as an argument. The deserialized object must be cast to an object variable
of type PurchaseOrder . The code then reads the values of the deserialized PurchaseOrder . Note that you can also
read the PO.xml file that is created to see the actual XML output.

Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports Microsoft.VisualBasic

' The XmlRootAttribute allows you to set an alternate name


' (PurchaseOrder) for the XML element and its namespace. By
' default, the XmlSerializer uses the class name. The attribute
' also allows you to set the XML namespace for the element. Lastly,
' the attribute sets the IsNullable property, which specifies whether
' the xsi:null attribute appears if the class instance is set to
' a null reference.
<XmlRootAttribute("PurchaseOrder", _
Namespace := "http://www.cpandl.com", IsNullable := False)> _
Public Class PurchaseOrder
Public ShipTo As Address
Public OrderDate As String
' The XmlArrayAttribute changes the XML element name
' from the default of "OrderedItems" to "Items".
<XmlArrayAttribute("Items")> _
Public OrderedItems() As OrderedItem
Public SubTotal As Decimal
Public ShipCost As Decimal
Public TotalCost As Decimal
End Class

Public Class Address


' The XmlAttribute instructs the XmlSerializer to serialize the
' Name field as an XML attribute instead of an XML element (the
' default behavior).
<XmlAttribute()> _
Public Name As String
Public Line1 As String

' Setting the IsNullable property to false instructs the


' XmlSerializer that the XML attribute will not appear if
' the City field is set to a null reference.
<XmlElementAttribute(IsNullable := False)> _
Public City As String
Public State As String
Public Zip As String
End Class

Public Class OrderedItem


Public ItemName As String
Public Description As String
Public UnitPrice As Decimal
Public Quantity As Integer
Public LineTotal As Decimal

' 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

Public Class Test


Public Shared Sub Main()
' Read and write purchase orders.
Dim t As New Test()
t.CreatePO("po.xml")
t.ReadPO("po.xml")
End Sub

Private Sub CreatePO(filename As String)


' Creates an instance of the XmlSerializer class;
' specifies the type of object to serialize.
Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
Dim writer As New StreamWriter(filename)
Dim po As New PurchaseOrder()

' Creates an address to ship and bill to.


Dim billAddress As New Address()
billAddress.Name = "Teresa Atkinson"
billAddress.Line1 = "1 Main St."
billAddress.City = "AnyTown"
billAddress.State = "WA"
billAddress.Zip = "00000"
' Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress
po.OrderDate = System.DateTime.Now.ToLongDateString()

' Creates an OrderedItem.


Dim i1 As New OrderedItem()
i1.ItemName = "Widget S"
i1.Description = "Small widget"
i1.UnitPrice = CDec(5.23)
i1.Quantity = 3
i1.Calculate()

' Inserts the item into the array.


Dim items(0) As OrderedItem
items(0) = i1
po.OrderedItems = items
' Calculates the total cost.
Dim subTotal As New Decimal()
Dim oi As OrderedItem
For Each oi In items
subTotal += oi.LineTotal
Next oi
po.SubTotal = subTotal
po.ShipCost = CDec(12.51)
po.TotalCost = po.SubTotal + po.ShipCost
' Serializes the purchase order, and close the TextWriter.
serializer.Serialize(writer, po)
writer.Close()
End Sub
End Sub

Protected Sub ReadPO(filename As String)


' Creates an instance of the XmlSerializer class;
' specifies the type of object to be deserialized.
Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
' If the XML document has been altered with unknown
' nodes or attributes, handles them with the
' UnknownNode and UnknownAttribute events.
AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
AddHandler serializer.UnknownAttribute, AddressOf _
serializer_UnknownAttribute

' A FileStream is needed to read the XML document.


Dim fs As New FileStream(filename, FileMode.Open)
' Declare an object variable of the type to be deserialized.
Dim po As PurchaseOrder
' Uses the Deserialize method to restore the object's state
' with data from the XML document.
po = CType(serializer.Deserialize(fs), PurchaseOrder)
' Reads the order date.
Console.WriteLine(("OrderDate: " & po.OrderDate))

' Reads the shipping address.


Dim shipTo As Address = po.ShipTo
ReadAddress(shipTo, "Ship To:")
' Reads the list of ordered items.
Dim items As OrderedItem() = po.OrderedItems
Console.WriteLine("Items to be shipped:")
Dim oi As OrderedItem
For Each oi In items
Console.WriteLine((ControlChars.Tab & oi.ItemName & _
ControlChars.Tab & _
oi.Description & ControlChars.Tab & oi.UnitPrice & _
ControlChars.Tab & _
oi.Quantity & ControlChars.Tab & oi.LineTotal))
Next oi
' Reads the subtotal, shipping cost, and total cost.
Console.WriteLine((ControlChars.Cr & New String _
(ControlChars.Tab, 5) & _
" Subtotal" & ControlChars.Tab & po.SubTotal & ControlChars.Cr & _
New String(ControlChars.Tab, 5) & " Shipping" & ControlChars.Tab & _
po.ShipCost & ControlChars.Cr & New String(ControlChars.Tab, 5) & _
" Total" & New String(ControlChars.Tab, 2) & po.TotalCost))
End Sub

Protected Sub ReadAddress(a As Address, label As String)


' Reads the fields of the Address.
Console.WriteLine(label)
Console.Write((ControlChars.Tab & a.Name & ControlChars.Cr & _
ControlChars.Tab & a.Line1 & ControlChars.Cr & ControlChars.Tab & _
a.City & ControlChars.Tab & a.State & ControlChars.Cr & _
ControlChars.Tab & a.Zip & ControlChars.Cr))
End Sub

Protected Sub serializer_UnknownNode(sender As Object, e As _


XmlNodeEventArgs)
Console.WriteLine(("Unknown Node:" & e.Name & _
ControlChars.Tab & e.Text))
End Sub

Protected Sub serializer_UnknownAttribute(sender As Object, _


e As XmlAttributeEventArgs)
Dim attr As System.Xml.XmlAttribute = e.Attr
Console.WriteLine(("Unknown attribute " & attr.Name & "='" & _
attr.Value & "'"))
End Sub 'serializer_UnknownAttribute
End Class 'Test
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

// The XmlRootAttribute allows you to set an alternate name


// (PurchaseOrder) for the XML element and its namespace. By
// default, the XmlSerializer uses the class name. The attribute
// also allows you to set the XML namespace for the element. Lastly,
// the attribute sets the IsNullable property, which specifies whether
// the xsi:null attribute appears if the class instance is set to
// a null reference.
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
// The XmlArrayAttribute changes the XML element name
// from the default of "OrderedItems" to "Items".
[XmlArrayAttribute("Items")]
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}

public class Address


{
// The XmlAttribute instructs the XmlSerializer to serialize the
// Name field as an XML attribute instead of an XML element (the
// default behavior).
[XmlAttribute]
public string Name;
public string Line1;

// Setting the IsNullable property to false instructs the


// XmlSerializer that the XML attribute will not appear if
// the City field is set to a null reference.
[XmlElementAttribute(IsNullable = false)]
public string City;
public string State;
public string Zip;
}

public class OrderedItem


{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal;

// Calculate is a custom method that calculates the price per item


// and stores the value in a field.
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}

public class Test


{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.CreatePO("po.xml");
t.ReadPO("po.xml");
}

private void CreatePO(string filename)


{
// Creates an instance of the XmlSerializer class;
// specifies the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po=new PurchaseOrder();

// Creates an address to ship and bill to.


Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Sets ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString();

// 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();

// Inserts the item into the array.


OrderedItem [] items = {i1};
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach(OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal) 12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serializes the purchase order, and closes the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
}

protected void ReadPO(string filename)


{
// Creates an instance of the XmlSerializer class;
// specifies the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
// If the XML document has been altered with unknown
// nodes or attributes, handles them with the
// UnknownNode and UnknownAttribute events.
serializer.UnknownNode+= new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute+= new
XmlAttributeEventHandler(serializer_UnknownAttribute);

// A FileStream is needed to read the XML document.


FileStream fs = new FileStream(filename, FileMode.Open);
// Declares an object variable of the type to be deserialized.
PurchaseOrder po;
// Uses the Deserialize method to restore the object's state
// with data from the XML document. */
po = (PurchaseOrder) serializer.Deserialize(fs);
// Reads the order date.
// Reads the order date.
Console.WriteLine ("OrderDate: " + po.OrderDate);

// Reads the shipping address.


Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Reads the list of ordered items.
OrderedItem [] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach(OrderedItem oi in items)
{
Console.WriteLine("\t"+
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Reads the subtotal, shipping cost, and total cost.
Console.WriteLine(
"\n\t\t\t\t\t Subtotal\t" + po.SubTotal +
"\n\t\t\t\t\t Shipping\t" + po.ShipCost +
"\n\t\t\t\t\t Total\t\t" + po.TotalCost
);
}

protected void ReadAddress(Address a, string label)


{
// Reads the fields of the Address.
Console.WriteLine(label);
Console.Write("\t"+
a.Name +"\n\t" +
a.Line1 +"\n\t" +
a.City +"\t" +
a.State +"\n\t" +
a.Zip +"\n");
}

protected void serializer_UnknownNode


(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
}

protected void serializer_UnknownAttribute


(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}

The XML output might resemble the following.


<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cpandl.com">
<ShipTo Name="Teresa Atkinson">
<Line1>1 Main St.</Line1>
<City>AnyTown</City>
<State>WA</State>
<Zip>00000</Zip>
</ShipTo>
<OrderDate>Wednesday, June 27, 2001</OrderDate>
<Items>
<OrderedItem>
<ItemName>Widget S</ItemName>
<Description>Small widget</Description>
<UnitPrice>5.23</UnitPrice>
<Quantity>3</Quantity>
<LineTotal>15.69</LineTotal>
</OrderedItem>
</Items>
<SubTotal>15.69</SubTotal>
<ShipCost>12.51</ShipCost>
<TotalCost>28.2</TotalCost>
</PurchaseOrder>

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.

<?xml version="1.0" encoding="utf-8"?>


<xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace=""
xmlns:xs="http://www.w3.org/2001/XMLSchema">

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.

Public Class Book


Public ISBN As String
End Class
' When an instance of the Book class is serialized, it might
' produce this XML:
' <ISBN>1234567890</ISBN>.

public class Book


{
public string ISBN;
}
// When an instance of the Book class is serialized, it might
// produce this XML:
// <ISBN>1234567890</ISBN>.

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.

Public Class TaxRates


< XmlElement(ElementName = "TaxRate")> _
Public ReturnTaxRate As Decimal
End Class

public class TaxRates{


[XmlElement(ElementName = "TaxRate")]
public decimal ReturnTaxRate;
}

For more information about attributes, see Attributes. For a list of attributes that control XML serialization, see
Attributes That Control XML Serialization.

Controlling Array Serialization


The XmlArrayAttribute and the XmlArrayItemAttribute attributes are designed to control the serialization of
arrays. Using these attributes, you can control the element name, namespace, and XML Schema (XSD) data type
(as defined in the World Wide Web Consortium [www.w3.org] document titled "XML Schema Part 2: Datatypes").
You can also specify the types that can be included in an array.
The XmlArrayAttribute will determine the properties of the enclosing XML element that results when an array is
serialized. For example, by default, serializing the array below will result in an XML element named Employees .
The Employees element will contain a series of elements named after the array type Employee .

Public Class Group


Public Employees() As Employee
End Class
Public Class Employee
Public Name As String
End Class

public class Group{


public Employee[] Employees;
}
public class Employee{
public string Name;
}

A serialized instance might resemble the following.

<Group>
<Employees>
<Employee>
<Name>Haley</Name>
</Employee>
</Employees >
</Group>

By applying a XmlArrayAttribute, you can change the name of the XML element, as follows.

Public Class Group


<XmlArray("TeamMembers")> _
Public Employees() As Employee
End Class

public class Group{


[XmlArray("TeamMembers")]
public Employee[] Employees;
}

The resulting XML might resemble the following.

<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

public class Group{


[XmlArrayItem("MemberName")]
public Employee[] Employees;
}

The resulting XML might resemble the following.

<Group>
<Employees>
<MemberName>Haley</MemberName>
</Employees>
</Group>

Serializing Derived Classes


Another use of the XmlArrayItemAttribute is to allow the serialization of derived classes. For example, another
class named Manager that derives from Employee can be added to the previous example. If you do not apply the
XmlArrayItemAttribute, the code will fail at run time because the derived class type will not be recognized. To
remedy this, apply the attribute twice, each time setting the Type property for each acceptable type (base and
derived).

Public Class Group


<XmlArrayItem(Type:=GetType(Employee)), _
XmlArrayItem(Type:=GetType(Manager))> _
Public Employees() As Employee
End Class
Public Class Employee
Public Name As String
End Class
Public Class Manager
Inherits Employee
Public Level As Integer
End Class

public class Group{


[XmlArrayItem(Type = typeof(Employee)),
XmlArrayItem(Type = typeof(Manager))]
public Employee[] Employees;
}
public class Employee{
public string Name;
}
public class Manager:Employee{
public int Level;
}

A serialized instance might resemble the following.


<Group>
<Employees>
<Employee>
<Name>Haley</Name>
</Employee>
<Employee xsi:type = "Manager">
<Name>Ann</Name>
<Level>3</Level>
<Employee>
</Employees >
</Group>

Serializing an Array as a Sequence of Elements


You can also serialize an array as a flat sequence of XML elements by applying a XmlElementAttribute to the field
returning the array as follows.

Public Class Group


<XmlElement> _
Public Employees() As Employee
End Class

public class Group{


[XmlElement]
public Employee[] Employees;
}

A serialized instance might resemble the following.

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

<xs:element minOccurs="0" maxOccurs ="1" name="Employees" type="ArrayOfEmployee" />

When the XmlElementAttribute is applied to the field, the resulting schema describes the element as follows.

<xs:element minOccurs="0" maxOccurs="unbounded" name="Employees" type="Employee" />

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.

Public Class Group


<XmlElement(Type:=GetType(Employee)), _
XmlElement(Type:=GetType(Manager))> _
Public Info As ArrayList
End Class

public class Group{


[XmlElement(Type = typeof(Employee)),
XmlElement(Type = typeof(Manager))]
public ArrayList Info;
}

Controlling Serialization of Classes Using XmlRootAttribute and


XmlTypeAttribute
There are two attributes that can be applied to a class (and only a class): XmlRootAttribute and XmlTypeAttribute.
These attributes are very similar. The XmlRootAttribute can be applied to only one class: the class that, when
serialized, represents the XML document's opening and closing element—in other words, the root element. The
XmlTypeAttribute, on the other hand, can be applied to any class, including the root class.
For example, in the previous examples, the Group class is the root class, and all its public fields and properties
become the XML elements found in the XML document. Therefore, there can be only one root class. By applying
the XmlRootAttribute, you can control the XML stream generated by the XmlSerializer. For example, you can
change the element name and namespace.
The XmlTypeAttribute allows you to control the schema of the generated XML. This capability is useful when you
need to publish the schema through an XML Web service. The following example applies both the
XmlTypeAttribute and the XmlRootAttribute to the same class.

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

<xs:element name="NewGroupName" type="NewTypeName">

In contrast, if you were to serialize an instance of the class, only NewGroupName would be found in the XML
document.

<NewGroupName>
. . .
</NewGroupName>

Preventing Serialization with the XmlIgnoreAttribute


There might be situations when a public property or field does not need to be serialized. For example, a field or
property could be used to contain metadata. In such cases, apply the XmlIgnoreAttribute to the field or property
and the XmlSerializer will skip over it.

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.

ATTRIBUTE APPLIES TO SPECIFIES

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.

XmlAttributeAttribute Public field, property, parameter, or The member will be serialized as an


return value. XML attribute.

XmlChoiceIdentifierAttribute Public field, property, parameter, or The member can be further


return value. disambiguated by using an
enumeration.

XmlElementAttribute Public field, property, parameter, or The field or property will be serialized
return value. as an XML element.

XmlEnumAttribute Public field that is an enumeration The element name of an enumeration


identifier. member.

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

XmlRootAttribute Public class declarations. Controls XML serialization of the


attribute target as an XML root
element. Use the attribute to further
specify the namespace and element
name.

XmlTextAttribute Public properties and fields. The property or field should be


serialized as XML text.

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);
}

The XML stream might resemble the following.

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

Dim myObject As MySerializableClass = New MySerializableClass()


' Insert code to set properties and fields of the object.
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass))
' To write to a file, create a StreamWriter object.
Dim myWriter As StreamWriter = New StreamWriter("myFileName.xml")
mySerializer.Serialize(myWriter, myObject)
myWriter.Close()

MySerializableClass myObject = new MySerializableClass();


// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new
XmlSerializer(typeof(MySerializableClass));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter("myFileName.xml");
mySerializer.Serialize(myWriter, myObject);
myWriter.Close();

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 .

5. Pass the XmlSerializerNamespaces to the Serialize method of the XmlSerializer .

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

Public Shared Sub Main()


Dim test As New Run()
test.SerializeObject("XmlNamespaces.xml")
End Sub 'Main

Public Sub SerializeObject(filename As String)


Dim mySerializer As New XmlSerializer(GetType(Books))
' Writing a file requires a TextWriter.
Dim myWriter As New StreamWriter(filename)

' Creates an XmlSerializerNamespaces and adds two


' prefix-namespace pairs.
Dim myNamespaces As New XmlSerializerNamespaces()
myNamespaces.Add("books", "http://www.cpandl.com")
myNamespaces.Add("money", "http://www.cohowinery.com")

' Creates a Book.


Dim myBook As New Book()
myBook.TITLE = "A Book Title"
Dim myPrice As New Price()
myPrice.price = CDec(9.95)
myPrice.currency = "US Dollar"
myBook.PRICE = myPrice
Dim myBooks As New Books()
myBooks.Book = myBook
mySerializer.Serialize(myWriter, myBooks, myNamespaces)
myWriter.Close()
End Sub
End Class

Public Class Books


<XmlElement([Namespace] := "http://www.cohowinery.com")> _
Public Book As Book
End Class 'Books

<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

Public Class Price


<XmlAttribute([Namespace] := "http://www.cpandl.com")> _
Public currency As String
Public <XmlElement([Namespace] := "http://www.cohowinery.com")> _
price As Decimal
End Class
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

public class Run


{
public static void Main()
{
Run test = new Run();
test.SerializeObject("XmlNamespaces.xml");
}
public void SerializeObject(string filename)
{
XmlSerializer mySerializer = new XmlSerializer(typeof(Books));
// Writing a file requires a TextWriter.
TextWriter myWriter = new StreamWriter(filename);

// Creates an XmlSerializerNamespaces and adds two


// prefix-namespace pairs.
XmlSerializerNamespaces myNamespaces =
new XmlSerializerNamespaces();
myNamespaces.Add("books", "http://www.cpandl.com");
myNamespaces.Add("money", "http://www.cohowinery.com");

// 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();
}
}

public class Books


{
[XmlElement(Namespace = "http://www.cohowinery.com")]
public Book Book;
}

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

Literal and Encoded Styles


The XML generated by an XML Web service can be formatted in either one of two ways, either literal or encoded,
as explained in Customizing SOAP Messages. Therefore there are two sets of attributes that control XML
serialization. The attributes listed in Attributes That Control XML Serialization are designed to control literal style
XML. The attributes listed in Attributes That Control Encoded SOAP Serialization control the encoded style. By
selectively applying these attributes, you can tailor an application to return either, or both styles. Furthermore,
these attributes can be applied (as appropriate) to return values and parameters.
Example of Using Both Styles
When you're creating an XML Web service, you can use both sets of attributes on the methods. In the following
code example, the class named MyService contains two XML Web service methods, MyLiteralMethod and
MyEncodedMethod . Both methods perform the same function: returning an instance of the Order class. In the
Order class, the XmlTypeAttribute and the SoapTypeAttribute attributes are both applied to the OrderID field, and
both attributes have their ElementName property set to different values.
To run the example, paste the code into a file with an .asmx extension, and place the file into a virtual directory
managed by Internet Information Services (IIS). From an HTML browser, such as Internet Explorer, type the name
of the computer, virtual directory, and file.

<%@ WebService Language="VB" Class="MyService" %>


Imports System
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Serialization
Public Class Order
' Both types of attributes can be applied. Depending on which type
' the method used, either one will affect the call.
<SoapElement(ElementName:= "EncodedOrderID"), _
XmlElement(ElementName:= "LiteralOrderID")> _
public OrderID As String
End Class

Public Class MyService


<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod() As Order
Dim myOrder As Order = New Order()
return myOrder
End Function
<WebMethod, SoapRpcMethod> _
public Function MyEncodedMethod() As Order
Dim myOrder As Order = New Order()
return myOrder
End Function
End Class
<%@ WebService Language="C#" Class="MyService" %>
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
public class Order{
// Both types of attributes can be applied. Depending on which type
// the method used, either one will affect the call.
[SoapElement(ElementName = "EncodedOrderID")]
[XmlElement(ElementName = "LiteralOrderID")]
public String OrderID;
}
public class MyService{
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod(){
Order myOrder = new Order();
return myOrder;
}
[WebMethod][SoapRpcMethod]
public Order MyEncodedMethod(){
Order myOrder = new Order();
return myOrder;
}
}

The following code example calls MyLiteralMethod . The element name is changed to "LiteralOrderID".

<?xml version="1.0" encoding="utf-8"?>


<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethodResponse xmlns="http://tempuri.org/">
<MyLiteralMethodResult>
<LiteralOrderID>string</LiteralOrderID>
</MyLiteralMethodResult>
</MyLiteralMethodResponse>
</soap:Body>
</soap:Envelope>

The following code example calls MyEncodedMethod . The element name is "EncodedOrderID".

<?xml version="1.0" encoding="utf-8"?>


<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="http://tempuri.org/" xmlns:types="http://tempuri.org/encodedTypes"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:MyEncodedMethodResponse>
<MyEncodedMethodResult href="#id1" />
</tns:MyEncodedMethodResponse>
<types:Order id="id1" xsi:type="types:Order">
<EncodedOrderID xsi:type="xsd:string">string</EncodedOrderID>
</types:Order>
</soap:Body>
</soap:Envelope>

Applying Attributes to Return Values


You can also apply attributes to return values to control the namespace, element name, and so forth. The following
code example applies the XmlElementAttribute attribute to the return value of the MyLiteralMethod method. Doing
so allows you to control the namespace and element name.
<WebMethod, SoapDocumentMethod> _
public Function MyLiteralMethod() As _
<XmlElement(Namespace:="http://www.cohowinery.com", _
ElementName:= "BookOrder")> _
Order
Dim myOrder As Order = New Order()
return myOrder
End Function

[return: XmlElement(Namespace = "http://www.cohowinery.com",


ElementName = "BookOrder")]
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod(){
Order myOrder = new Order();
return myOrder;
}

When invoked, the code returns XML that resembles the following.

<?xml version="1.0" encoding="utf-8"?>


<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethodResponse xmlns="http://tempuri.org/">
<BookOrder xmlns="http://www.cohowinery.com">
<LiteralOrderID>string</LiteralOrderID>
</BookOrder>
</MyLiteralMethodResponse>
</soap:Body>
</soap:Envelope>

Attributes Applied to Parameters


You can also apply attributes to parameters to specify namespace, element name and so forth. The following code
example adds a parameter to the MyLiteralMethodResponse method, and applies the XmlAttributeAttribute
attribute to the parameter. The element name and namespace are both set for the parameter.

<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

[return: XmlElement(Namespace = "http://www.cohowinery.com",


ElementName = "BookOrder")]
[WebMethod][SoapDocumentMethod]
public Order MyLiteralMethod([XmlElement("MyOrderID",
Namespace="http://www.microsoft.com")] string ID){
Order myOrder = new Order();
myOrder.OrderID = ID;
return myOrder;
}

The SOAP request would resemble the following.


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<MyLiteralMethod xmlns="http://tempuri.org/">
<MyOrderID xmlns="http://www.microsoft.com">string</MyOrderID>
</MyLiteralMethod>
</soap:Body>
</soap:Envelope>

Applying Attributes to Classes


If you need to control the namespace of elements that correlate to classes, you can apply XmlTypeAttribute ,
XmlRootAttribute , and SoapTypeAttribute , as appropriate. The following code example applies all three to the
Order class.

<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

[XmlType("BigBooksService", Namespace = "http://www.cpandl.com")]


[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 String OrderID;
}

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:element name="BookOrderForm" type="s0:BigBookService" />


- <s:complexType name="BigBookService">
- <s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="LiteralOrderID" type="s:string" />
</s:sequence>

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

' Serializes a class named Group as a SOAP message.


Dim myTypeMapping As XmlTypeMapping = (New SoapReflectionImporter(). _
ImportTypeMapping(GetType(Group))

// Serializes a class named Group as a SOAP message.


XmlTypeMapping myTypeMapping = (new SoapReflectionImporter().
ImportTypeMapping(typeof(Group));

4. Create an instance of the XmlSerializer class by passing the XmlTypeMapping to the


XmlSerializer(XmlTypeMapping) constructor.

Dim mySerializer As XmlSerializer = New XmlSerializer(myTypeMapping)

XmlSerializer mySerializer = new XmlSerializer(myTypeMapping);

5. Call the Serialize or Deserialize method.

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)

// Serializes a class named Group as a SOAP message.


XmlTypeMapping myTypeMapping = (new SoapReflectionImporter().ImportTypeMapping(typeof(Group));
XmlSerializer mySerializer = 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;

public class Group


{
[SoapAttribute (Namespace = "http://www.cpandl.com")]
public string GroupName;

[SoapAttribute(DataType = "base64Binary")]
public Byte [] GroupNumber;

[SoapAttribute(DataType = "date", AttributeName = "CreationDate")]


public DateTime Today;
[SoapElement(DataType = "nonNegativeInteger", ElementName = "PosInt")]
public string PostitiveInt;
// This is ignored when serialized unless it is overridden.
[SoapIgnore]
[SoapIgnore]
public bool IgnoreThis;

public GroupType Grouptype;

[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 abstract class Vehicle


{
public string licenseNumber;
public DateTime makeDate;
}

public class Car: Vehicle


{
}

public enum GroupType


{
// These enums can be overridden.
small,
large
}

public class Run


{
public static void Main()
{
Run test = new Run();
test.SerializeOriginal("SoapOriginal.xml");
test.SerializeOverride("SoapOverrides.xml");
test.DeserializeOriginal("SoapOriginal.xml");
test.DeserializeOverride("SoapOverrides.xml");

}
public void SerializeOriginal(string filename)
{
// Creates an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);

// Writing the file requires a TextWriter.


TextWriter writer = new StreamWriter(filename);

// Creates an instance of the class that will be serialized.


Group myGroup = new Group();

// Sets the object properties.


myGroup.GroupName = ".NET";

Byte [] hexByte = new Byte[2]{Convert.ToByte(100),


Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
Convert.ToByte(50)};
myGroup.GroupNumber = hexByte;

DateTime myDate = new DateTime(2002,5,2);


myGroup.Today = myDate;

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");

// Serializes the class and closes the TextWriter.


mySerializer.Serialize(writer, myGroup);
writer.Close();
}

public void SerializeOverride(string filename)


{
// Creates an instance of the XmlSerializer class
// that overrides the serialization.
XmlSerializer overRideSerializer = CreateOverrideSerializer();

// Writing the file requires a TextWriter.


TextWriter writer = new StreamWriter(filename);

// Creates an instance of the class that will be serialized.


Group myGroup = new Group();

// Sets the object properties.


myGroup.GroupName = ".NET";

Byte [] hexByte = new Byte[2]{Convert.ToByte(100),


Convert.ToByte(50)};
myGroup.GroupNumber = hexByte;

DateTime myDate = new DateTime(2002,5,2);


myGroup.Today = myDate;

myGroup.PostitiveInt= "10000";
myGroup.IgnoreThis=true;
myGroup.Grouptype= GroupType.small;
Car thisCar =(Car) myGroup.myCar("1234566");

// Serializes the class and closes the TextWriter.


overRideSerializer.Serialize(writer, myGroup);
writer.Close();
}

public void DeserializeOriginal(string filename)


{
// Creates an instance of the XmlSerializer class.
XmlTypeMapping myMapping =
(new SoapReflectionImporter().ImportTypeMapping(
typeof(Group)));
XmlSerializer mySerializer =
new XmlSerializer(myMapping);

TextReader reader = new StreamReader(filename);

// Deserializes and casts the object.


Group myGroup;
myGroup = (Group) mySerializer.Deserialize(reader);

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();
}

public void DeserializeOverride(string filename)


{
// Creates an instance of the XmlSerializer class.
XmlSerializer overRideSerializer = CreateOverrideSerializer();
// Reading the file requires a TextReader.
TextReader reader = new StreamReader(filename);

// Deserializes and casts the object.


Group myGroup;
myGroup = (Group) overRideSerializer.Deserialize(reader);

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);
}

private XmlSerializer CreateOverrideSerializer()


{
SoapAttributeOverrides mySoapAttributeOverrides =
new SoapAttributeOverrides();
SoapAttributes soapAtts = new SoapAttributes();

SoapElementAttribute mySoapElement = new SoapElementAttribute();


mySoapElement.ElementName = "xxxx";
soapAtts.SoapElement = mySoapElement;
mySoapAttributeOverrides.Add(typeof(Group), "PostitiveInt",
soapAtts);

// Overrides the IgnoreThis property.


SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
soapAtts = new SoapAttributes();
soapAtts.SoapIgnore = false;
mySoapAttributeOverrides.Add(typeof(Group), "IgnoreThis",
soapAtts);

// Overrides the GroupType enumeration.


soapAtts = new SoapAttributes();
SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
xSoapEnum.Name = "Over1000";
soapAtts.SoapEnum = xSoapEnum;

// Adds the SoapAttributes to the


// mySoapAttributeOverridesrides.
mySoapAttributeOverrides.Add(typeof(GroupType), "large",
soapAtts);

// Creates a second enumeration and adds it.


soapAtts = new SoapAttributes();
xSoapEnum = new SoapEnumAttribute();
xSoapEnum.Name = "ZeroTo1000";
soapAtts.SoapEnum = xSoapEnum;
mySoapAttributeOverrides.Add(typeof(GroupType), "small",
soapAtts);

// Overrides the Group type.


soapAtts = new SoapAttributes();
SoapTypeAttribute soapType = new SoapTypeAttribute();
soapType.TypeName = "Team";
soapAtts.SoapType = soapType;
mySoapAttributeOverrides.Add(typeof(Group),soapAtts);
mySoapAttributeOverrides.Add(typeof(Group),soapAtts);

// Creates an XmlTypeMapping that is used to create an instance


// of the XmlSerializer class. Then returns the XmlSerializer.
XmlTypeMapping myMapping = (new SoapReflectionImporter(
mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));

XmlSerializer ser = new XmlSerializer(myMapping);


return ser;
}
}

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.

ATTRIBUTE APPLIES TO SPECIFIES

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.

SoapEnumAttribute Public field that is an enumeration The element name of an enumeration


identifier. member.

SoapIgnoreAttribute Public properties and fields. The property or field should be


ignored when the containing class is
serialized.

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.

SoapTypeAttribute Public class declarations. The class should be serialized as an


XML type.

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>

Attributes and Elements


The following sections describe attributes, child elements, and parent elements.
Attributes
None.
Child Elements
ELEMENT DESCRIPTION

<dateTimeSerialization> Element Determines the serialization mode of DateTime objects.

<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

Determines the serialization mode of DateTime objects.


<configuration>
<dateTimeSerialization>

Syntax
<dateTimeSerialization
mode = "Roundtrip" | "Local"
/>

Attributes and Elements


The following sections describe attributes, child elements, and parent elements.
Attributes
ATTRIBUTES DESCRIPTION

mode Optional. Specifies the serialization mode. Set to one of the


DateTimeSerializationSection.DateTimeSerializationMode
values. The default is RoundTrip.

Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION

system.xml.serialization The top-level element for controlling XML serialization.

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

<system.xml.serialization> Element The top-level element for controlling XML serialization.

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]"/>

Attributes and Elements


The following sections describe attributes, child elements, and parent elements.
Attributes
ATTRIBUTE DESCRIPTION

name A simple name that is used to find the instance.

type Required. Specifies the schema extension class to add. The


type attribute value must be on one line, and include the fully
qualified type name. When the assembly is placed in the
Global Assembly Cache (GAC), it must also include the
version, culture, and public key token of the signed assembly.

Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION

<xmlSchemaImporterExtensions> Contains the types that are used by the XmlSchemaImporter.

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

Specifies whether an additional check of progress of the XmlSerializer is done.


<configuration>
<system.xml.serialization>

Syntax
<xmlSerializer checkDeserializerAdvance = "true"|"false" />

Attributes and Elements


The following sections describe attributes, child elements, and parent elements.
Attributes
ATTRIBUTE DESCRIPTION

checkDeserializeAdvances Specifies whether the progress of the XmlSerializer is checked.


Set the attribute to "true" or "false". The default is "true".

useLegacySerializationGeneration Specifies whether the XmlSerializer uses legacy serialization


generation which generates assemblies by writing C# code to
a file and then compiling it to an assembly. The default is
false.

Child Elements
None.
Parent Elements
ELEMENT DESCRIPTION

<system.xml.serialization> Element Contains configuration settings for the XmlSerializer and


XmlSchemaImporter classes.

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.

/d[ebug] Generates an image that can be used with a debugger.

/f[orce] Forces the overwriting of an existing assembly of the same


name. The default is false.

/help or /? Displays command syntax and options for the tool.

/k[eep] Suppresses the deletion of the generated source files and


other temporary files after they have been compiled into the
serialization assembly. This can be used to determine whether
the tool is generating serialization code for a particular type.

/n[ologo] Suppresses the display of the Microsoft startup banner.

/o[ut]:path Specifies the directory in which to save the generated


assembly. Note: The name of the generated assembly is
composed of the name of the input assembly plus
"xmlSerializers.dll".

/p[roxytypes] Generates serialization code only for the XML Web service
proxy types.

/r[eference]:assemblyfiles Specifies the assemblies that are referenced by the types


requiring XML serialization. Accepts multiple assembly files
separated by commas.

/s[ilent] Suppresses the display of success messages.


OPTION DESCRIPTION

/t[ype]:type Generates serialization code only for the specified type.

/v[erbose] Displays verbose output for debugging. Lists types from the
target assembly that cannot be serialized with the
XmlSerializer.

/? Displays command syntax and options for the tool.

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.

If you specify an XDR schema file (.xdr extension), Xsd.exe


converts the XDR schema to an XSD schema. The output file
has the same name as the XDR schema, but with the .xsd
extension.

If you specify an XML file (.xml extension), Xsd.exe infers a


schema from the data in the file and produces an XSD
schema. The output file has the same name as the XML file,
but with the .xsd extension.

If you specify an XML schema file (.xsd extension), Xsd.exe


generates source code for runtime objects that correspond to
the XML schema.

If you specify a runtime assembly file (.exe or .dll extension),


Xsd.exe generates schemas for one or more types in that
assembly. You can use the /type option to specify the
types for which to generate schemas. The output schemas
are named schema0.xsd, schema1.xsd, and so on. Xsd.exe
produces multiple schemas only if the given types specify a
namespace using the XMLRoot custom attribute.

General Options
OPTION DESCRIPTION

/h[elp] Displays command syntax and options for the tool.


OPTION DESCRIPTION

/o[utputdir]:directory Specifies the directory for output files. This argument can
appear only once. The default is the current directory.

/? Displays command syntax and options for the tool.

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

XSD File Options


You must specify only one of the following options for .xsd files.

OPTION DESCRIPTION

/c[lasses] Generates classes that correspond to the specified schema.


To read XML data into the object, use the
System.Xml.Serialization.XmlSerializer.Deserializer
method.

/d[ataset] Generates a class derived from DataSet that corresponds to


the specified schema. To read XML data into the derived
class, use the System.Data.DataSet.ReadXml method.

You can also specify any of the following options for .xsd files.

OPTION DESCRIPTION

/e[lement]:element Specifies the element in the schema to generate code for. By


default all elements are typed. You can specify this argument
more than once.

/enableDataBinding Implements the INotifyPropertyChanged interface on all


generated types to enable data binding. The short form is
/edb .

/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).

/f[ields] Generates fields instead of properties. By default, properties


are generated.

/l[anguage]:language Specifies the programming language to use. Choose from


CS (C#, which is the default), VB (Visual Basic), JS
(JScript), or VJS (Visual J#). You can also specify a fully
qualified name for a class implementing
System.CodeDom.Compiler.CodeDomProvider

/n[amespace]:namespace Specifies the runtime namespace for the generated types. The
default namespace is Schemas .
OPTION DESCRIPTION

/nologo Suppresses the banner.

/order Generates explicit order identifiers on all particle members.

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

DLL and EXE File Options


OPTION DESCRIPTION

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

Setting Options with an XML File


By using the /parameters switch, you can specify a single XML file that sets various options. The options you can
set depend on how you are using the XSD.exe tool. Choices include generating schemas, generating code files, or
generating code files that include DataSet features. For example, you can set the <assembly\> element to the
name of an executable (.exe) or type library (.dll) file when generating a schema, but not when generating a code
file. The following XML shows how to use the <generateSchemas\> element with a specified executable:

<!-- This is in a file named GenerateSchemas.xml. -->


<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
<generateSchemas>
<assembly>ConsoleApplication1.exe</assembly>
</generateSchemas>
</xsd>

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:

<!-- This is in a file named GenerateSchemaFromType.xml. -->


<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
<generateSchemas>
<type>IDItems</type>
</generateSchemas>
</xsd>

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

<assembly> Specifies an assembly to generate the schema from.

<type> Specifies a type found in an assembly to generate a schema


for.

<xml> Specifies an XML file to generate a schema for.

<xdr> Specifies an XDR file to generate a schema for.

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

<element> Specifies an element in the .xsd file to generate code for.

<schemaImporterExtensions> Specifies a type derived from the SchemaImporterExtension


class.

<schema> Specifies a XML Schema file to generate code for. Multiple


XML Schema files can be specified using multiple <schema>
elements.

The following table shows the attributes that can also be used with the <generateClasses\> element.

ATTRIBUTE DESCRIPTION

language Specifies the programming language to use. Choose from


CS (C#, the default), VB (Visual Basic), JS (JScript), or
VJS (Visual J#). You can also specify a fully qualified name
for a class that implements CodeDomProvider.

namespace Specifies the namespace for the generated code. The


namespace must conform to CLR standards (for example, no
spaces or backslash characters).

options One of the following values: none , properties (generates


properties instead of public fields), order , or
enableDataBinding (see the /order and
/enableDataBinding switches in the preceding XSD File
Options section.

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 language='VB' namespace='Microsoft.Serialization.Examples' enableLinqDataSet='true'>

</generateDataSet>

</xsd>

Options you can set for the <generateDataSet\> element include the following.

ELEMENT DESCRIPTION

<schema> Specifies an XML Schema file to generate code for. Multiple


XML Schema files can be specified using multiple <schema>
elements.

The following table shows the attributes that can be used with the <generateDataSet\> element.

ATTRIBUTE DESCRIPTION

enableLinqDataSet Specifies that the generated DataSet can be queried against


using LINQ to DataSet. The default value is false.
ATTRIBUTE DESCRIPTION

language Specifies the programming language to use. Choose from


CS (C#, the default), VB (Visual Basic), JS (JScript), or
VJS (Visual J#). You can also specify a fully qualified name
for a class that implements CodeDomProvider.

namespace Specifies the namespace for the generated code. The


namespace must conform to CLR standards (for example, no
spaces or backslash characters).

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

<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/' output='MyOutputDirectory'>


<generateClasses>
<element>IDItems</element>
</generateClasses>
</xsd>

The following table shows the attributes that can also be used with the \<xsd> element.

ATTRIBUTE DESCRIPTION

output The name of a directory where the generated schema or code


file will be placed.

nologo Suppresses the banner. Set to true or false .

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.

xsd myFile.xml /outputdir:myOutputDir

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.

xsd /dataset /language:CS XSDSchemaFile.xsd

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

This section demonstrates serializing objects in the .NET Framework.

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.

1. Open File Explorer and navigate to the \CS subdirectory.


2. Right-click the icon for the GenericsService subdirectory, and select Sharing and Security.
3. In the Web Sharing tab, select Share this Folder.

IMPORTANT
Take note of the virtual directory name that is listed in the Aliases pane, because you will need it to run the sample.

To build the sample using Internet Information Services


1. Open the Internet Information Services management snap-in and expand Web Sites.
2. Left-click Default Web Site, select New, and then select Virtual Directory? to create the Virtual
Directory Creation Wizard.
3. Click Next, enter the public alias for your virtual directory, and click Next.
4. Enter the path to the directory where you saved the sample (normally the \CS\GenericsService subdirectory)
and click Next. Click Next to finish the wizard.
IMPORTANT
Take note of the virtual directory name that is listed in the Alias pane, because you will need it to run the sample.

To run the sample


1. Open a browser window and select its address bar.
2. Type http://localhost/[virtual directory]/Service.asmx, where [virtual directory] represents the virtual
directory you created when you built 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

You might also like