This documentation is archived and is not being maintained.

XmlSerializer Class

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

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

public class XmlSerializer

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. For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

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 (Xsd.exe) to generate the classes based on an existing XML Schema definition (XSD) document. If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized.

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 and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. In either case, the classes are annotated with custom attributes to instruct the XmlSerializer how to map between the XML schema system and the common language runtime. At runtime, instances of the classes can be serialized into XML documents that follow the given schema. Likewise, these XML documents can be deserialized into runtime objects. Note that the XML schema is optional, and not required at design time or 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. For a complete list of similar attributes, see Attributes That Control XML Serialization. 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 ( document, "Simple Object Access Protocol (SOAP) 1.1", you must construct the XmlSerializer with an XmlTypeMapping. To further control the encoded SOAP XML, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

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.

No code example is currently available or this language may not be supported.

The serialized, XML output looks like this:

  <ObjectName>My String</ObjectName>

If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

No code example is currently available or this language may not be supported.

Another option is to 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.

No code example is currently available or this language may not be supported.

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 details, see the XmlAttributeOverrides class and How to: Control Serialization of Derived Classes.

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.


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:


XmlSerializer.XmlSerializer(Type, String)

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.

No code example is currently available or this language may not be supported.

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

The following example contains two main classes: PurchaseOrder and Test. The PurchaseOrder class contains information about a single purchase. The Test class contains the methods that create the purchase order, and that read the created purchase order.

No code example is currently available or this language may not be supported.
#using <mscorlib.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;

public __gc class Address;
public __gc class OrderedItem;

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element 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(S"PurchaseOrder", Namespace=S"", 
IsNullable = false)]
public __gc class PurchaseOrder
   Address* ShipTo;
   String* OrderDate; 
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   OrderedItem* OrderedItems[];
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;   

public __gc class Address
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
   String* Name;
   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)]
   String* City;
   String* State;
   String* Zip;

public __gc class OrderedItem
   String* ItemName;
   String* Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   void Calculate()
      LineTotal = UnitPrice * Quantity;

public __gc class Test
   static void main()
      // Read and write purchase orders.
      Test* t = new Test();

   void CreatePO(String* filename)
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer* serializer = 
      new XmlSerializer(__typeof(PurchaseOrder));
      TextWriter* writer = new StreamWriter(filename);
      PurchaseOrder* po=new PurchaseOrder();

      // Create an address to ship and bill to.
      Address* billAddress = new Address();
      billAddress->Name = S"Teresa Atkinson";
      billAddress->Line1 = S"1 Main St.";
      billAddress->City = S"AnyTown";
      billAddress->State = S"WA";
      billAddress->Zip = S"00000";
      // Set ShipTo and BillTo to the same addressee.
      po->ShipTo = billAddress;
      po->OrderDate = System::DateTime::Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem* i1 = new OrderedItem();
      i1->ItemName = S"Widget S";
      i1->Description = S"Small widget";
      i1->UnitPrice = (Decimal) 5.23;
      i1->Quantity = 3;

      // Insert the item into the array.
      OrderedItem* items[] = {i1};
      po->OrderedItems = items;
      // Calculate the total cost.
      Decimal subTotal = Decimal( 0 );
      System::Collections::IEnumerator* myEnum = items->GetEnumerator();
      while (myEnum->MoveNext())
         OrderedItem* oi = __try_cast<OrderedItem*>(myEnum->Current);
         subTotal = subTotal + oi->LineTotal;
      po->SubTotal = subTotal;
      po->ShipCost = (Decimal) 12.51; 
      po->TotalCost = po->SubTotal + po->ShipCost; 
      // Serialize the purchase order, and close the TextWriter.
      serializer->Serialize(writer, po);

   void ReadPO(String* filename)
      // Create an instance of the XmlSerializer class;
      // specify 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, handle them with the 
      UnknownNode and UnknownAttribute events.*/
      serializer->UnknownNode+= new 
      XmlNodeEventHandler(this, &Test::serializer_UnknownNode);
      serializer->UnknownAttribute+= new 
      XmlAttributeEventHandler(this, &Test::serializer_UnknownAttribute);

      // A FileStream is needed to read the XML document.
      FileStream* fs = new FileStream(filename, FileMode::Open);
      // Declare an object variable of the type to be deserialized.
      PurchaseOrder* po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = dynamic_cast<PurchaseOrder*> (serializer->Deserialize(fs));
      // Read the order date.
      Console::WriteLine (S"OrderDate: {0}", po->OrderDate);

      // Read the shipping address.
      Address* shipTo = po->ShipTo;
      ReadAddress(shipTo, S"Ship To:");
      // Read the list of ordered items.
      OrderedItem* items[] = po->OrderedItems;
      Console::WriteLine(S"Items to be shipped:");
      System::Collections::IEnumerator* myEnum1 = items->GetEnumerator();
      while (myEnum1->MoveNext())
          OrderedItem* oi = __try_cast<OrderedItem*>(myEnum1->Current);
         Console::WriteLine(S"\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, __box(oi->UnitPrice), __box(oi->Quantity), oi->LineTotal);
      // Read the subtotal, shipping cost, and total cost.
      Console::WriteLine(S"\t\t\t\t\t Subtotal\t{0}", __box(po->SubTotal));
      Console::WriteLine(S"\t\t\t\t\t Shipping\t{0}", __box(po->ShipCost)); 
      Console::WriteLine(S"\t\t\t\t\t Total\t\t{0}", __box(po->TotalCost));

   void ReadAddress(Address* a, String* label)
      // Read the fields of the Address object.
      Console::WriteLine(S"\t{0}", a->Name );
      Console::WriteLine(S"\t{0}", a->Line1);
      Console::WriteLine(S"\t{0}", a->City);
      Console::WriteLine(S"\t{0}", a->State);
      Console::WriteLine(S"\t{0}", a->Zip );

   void serializer_UnknownNode(Object* /*sender*/, XmlNodeEventArgs* e)
      Console::WriteLine(S"Unknown Node:{0}\t{1}", e->Name, e->Text);

   void serializer_UnknownAttribute(Object* /*sender*/, XmlAttributeEventArgs* e)
      System::Xml::XmlAttribute* attr = e->Attr;
      Console::WriteLine(S"Unknown attribute {0}='{1}'", attr->Name, attr->Value);

int main()


This type is thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0