Aracılığıyla paylaş


XmlSerializer Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Inheritance Hierarchy

System.Object
  System.Xml.Serialization.XmlSerializer

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

Syntax

'Declaration
Public Class XmlSerializer
public class XmlSerializer

The XmlSerializer type exposes the following members.

Constructors

  Name Description
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer() Infrastructure. Initializes a new instance of the XmlSerializer class.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(XmlTypeMapping) Initializes an instance of the XmlSerializer class using an object that maps one type to another.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(Type, array<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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 XmlSerializer(Type, XmlAttributeOverrides, array<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

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 CanDeserialize Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.
Protected method CreateReader Infrastructure. Returns an object used to read the XML document to be serialized.
Protected method CreateWriter Infrastructure. When overridden in a derived class, returns a writer used to serialize the object.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Deserialize(Stream) Deserializes the XML document contained by the specified Stream.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Deserialize(TextReader) Deserializes the XML document contained by the specified TextReader.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Deserialize(XmlReader) Deserializes the XML document contained by the specified XmlReader.
Protected method Deserialize(XmlSerializationReader) Infrastructure. Deserializes the XML document contained by the specified XmlSerializationReader.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Finalize Allows 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 memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 FromMappings(array<XmlMapping[]) Infrastructure. Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 FromMappings(array<XmlMapping[], Type) Infrastructure. Returns an instance of the XmlSerializer class from the specified mappings.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 FromTypes Returns an array of XmlSerializer objects created from an array of types.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetType Gets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method Serialize(Object, XmlSerializationWriter) Infrastructure. Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(Stream, Object) Serializes the specified Object and writes the XML document to a file using the specified Stream.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(TextWriter, Object) Serializes the specified Object and writes the XML document to a file using the specified TextWriter.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(XmlWriter, Object) Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 Serialize(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 methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

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 in the form of XmlElement or XmlAttribute objects.

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 of type XmlElement, XmlAttribute or XmlNode in your strongly-typed classes, 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 XmlElement objects or apply an XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute 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
public class MyClass
{
    public MyObject MyObjectProperty;
}
public class MyObject
{
    public string ObjectName;
}

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
public class OptionalOrder
{
    // This field should not be serialized 
    // if it is uninitialized.
    public string FirstOrder;

    // Use the XmlIgnoreAttribute to ignore the 
    // special field named "FirstOrderSpecified".
    [System.Xml.Serialization.XmlIgnoreAttribute]
    public bool FirstOrderSpecified;
}

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 (such as CollectionBase) 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. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

Hashtable serializers = new Hashtable();

// Use the constructor that takes a type and XmlRootAttribute.
XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);

// Implement a method named GenerateKey that creates unique keys 
// for each instance of the XmlSerializer. The code should take 
// into account all parameters passed to the XmlSerializer 
// constructor.
object key = GenerateKey(typeof(MyClass), myRoot);

// Check the local cache for a matching serializer.
XmlSerializer ser = (XmlSerializer)serializers[key];
if (ser == null) 
{
    ser = new XmlSerializer(typeof(MyClass), myRoot);
    // Cache the serializer.
    serializers[key] = ser;
}
else
{
    // Use the serializer to serialize, or deserialize.
}
Dim serializers As New Hashtable()

' Use the constructor that takes a type and XmlRootAttribute.
Dim s As New XmlSerializer(GetType([MyClass]), myRoot)

' Implement a method named GenerateKey that creates unique keys 
' for each instance of the XmlSerializer. The code should take 
' into account all parameters passed to the XmlSerializer 
' constructor.
Dim key As Object = GenerateKey(GetType([MyClass]), myRoot)

' Check the local cache for a matching serializer.
Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer)

If ser Is Nothing Then
    ser = New XmlSerializer(GetType([MyClass]), myRoot)
    ' Cache the serializer.
    serializers(key) = ser
Else 
    ' Use the serializer to serialize, or deserialize.
End If

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

Platform Notes

Silverlight for Windows Phone Silverlight for 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.

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

This type is thread safe.