XmlSerializer Class

July 28, 2014

Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML.

System.Object
  System.Xml.Serialization.XmlSerializer

Namespace:  System.Xml.Serialization
Assembly:  System.Xml.Serialization (in System.Xml.Serialization.dll)

'Declaration
Public Class XmlSerializer

The XmlSerializer type exposes the following members.

  NameDescription
Protected methodXmlSerializerInfrastructure. Initializes a new instance of the XmlSerializer class.
Public methodXmlSerializer(Type)Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents and deserialize XML documents into objects of the specified type.
Public methodXmlSerializer(XmlTypeMapping)Initializes an instance of the XmlSerializer class using an object that maps one type to another.
Public methodXmlSerializer(Type, String)Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents and deserialize XML documents into objects of the specified type. Specifies the default namespace for all the XML elements.
Public methodXmlSerializer(Type, Type())Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents and deserialize XML documents into objects of a specified type. If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.
Public methodXmlSerializer(Type, XmlAttributeOverrides)Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents and deserialize XML documents into objects of the specified type. Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.
Public methodXmlSerializer(Type, XmlRootAttribute)Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents and deserialize an XML document into object of the specified type. It also specifies the class to use as the XML root element.
Public methodXmlSerializer(Type, XmlAttributeOverrides, Type(), XmlRootAttribute, String)Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances and deserialize XML document instances into objects of type Object. Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.
Top

  NameDescription
Public methodCanDeserializeGets a value that indicates whether this XmlSerializer can deserialize a specified XML document.
Public methodDeserialize(Stream)Deserializes the XML document contained by the specified Stream.
Public methodDeserialize(TextReader)Deserializes the XML document contained by the specified TextReader.
Public methodDeserialize(XmlReader)Deserializes the XML document contained by the specified XmlReader.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberFromMappings(XmlMapping())Infrastructure. Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.
Public methodStatic memberFromMappings(XmlMapping(), Type)Infrastructure. Returns an instance of the XmlSerializer class from the specified mappings.
Public methodStatic memberFromTypesReturns an array of XmlSerializer objects created from an array of types.
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSerialize(Stream, Object)Serializes the specified Object and writes the XML document to a file using the specified Stream.
Public methodSerialize(TextWriter, Object)Serializes the specified Object and writes the XML document to a file using the specified TextWriter.
Public methodSerialize(XmlWriter, Object)Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.
Public methodSerialize(Stream, Object, XmlSerializerNamespaces)Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.
Public methodSerialize(TextWriter, Object, XmlSerializerNamespaces)Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.
Public methodSerialize(XmlWriter, Object, XmlSerializerNamespaces)Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer.

The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML.

To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. The XmlSerializer provides the bridge between these two technologies at both design time and runtime.

Controlling Generated XML

To control the generated XML, you can apply special attributes to classes and members. For example, to specify a different XML element name, apply an XmlElementAttribute to a public field or property, and set the ElementName property. You can also implement the IXmlSerializable interface to control the XML output.

If the XML generated must conform to section 5 of the World Wide Consortium (www.w3.org) document, "Simple Object Access Protocol (SOAP) 1.1", you must construct the XmlSerializer with an XmlTypeMapping.

With the XmlSerializer you can take advantage of working with strongly-typed classes and still have the flexibility of XML. Using fields or properties, you can read parts of the XML document directly into XML objects.

If you work with extensible XML schemas, you can also use the XmlAnyElementAttribute and XmlAnyAttributeAttribute attributes to serialize and deserialize elements or attributes that are not found in the original schema. To use the objects, apply an XmlAnyElementAttribute to a field that returns an array of objects or apply an XmlAnyAttributeAttribute to a field that returns an array of objects.

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 returns an instance of the second class.

Public Class MyClass
    Public MyObjectProperty As MyObject
End Class

Public Class MyObject
    Public ObjectName As String
End Class

The serialized, XML output looks like the following code.

<MyClass>
  <MyObjectProperty>
  <ObjectName>My String</ObjectName>
  </MyObjectProperty>
</MyClass>

If a schema includes an element that is optional (minOccurs = '0') or if the schema includes a default value, use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". This is shown in the following example.

Public Class OptionalOrder
    ' This field's value should not be serialized 
    ' if it is uninitialized.
    Public FirstOrder As String

    ' Use the XmlIgnoreAttribute to ignore the 
    ' special field named "FirstOrderSpecified".
    <System.Xml.Serialization.XmlIgnoreAttribute> _
    Public FirstOrderSpecified As Boolean
End Class

Overriding Default Serialization

You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the XmlAttributes class. Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. For more information, see the XmlAttributeOverrides class.

To serialize an object, call the Serialize method. To deserialize an object, call the Deserialize method.

To add XML namespaces to an XML document, see XmlSerializerNamespaces.

NoteNote:

The XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator or one of that type's bases. A class that implements ICollection in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer and it must have a public Count property of type integer. The parameter to the Add method must be the same type as is 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, not by calling GetEnumerator.

You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object.

Dynamically Generated Assemblies

To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:

If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors.

Serialization of ArrayList and Generic List

The XmlSerializer cannot serialize or deserialize the following:

Serialization of Enumerations of Unsigned Long

The XmlSerializer cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (ulong in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. For example, the following code cannot be serialized.

public enum LargeNumbers: ulong
{
    a = 9223372036854775808
}
// At runtime, the following code will fail.
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));

Objects marked with the Obsolete Attribute no longer serialized

In the .NET Framework 3.5 the XmlSerializer class no longer serializes objects that are marked as [Obsolete].

Version Notes

Windows Phone

 When you use XML serialization on objects of type XElement, extra XElement tags are added to the beginning and end of the XML content.

Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

This type is thread safe.

Show:
© 2014 Microsoft