Export (0) Print
Expand All

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)

'Declaration
Public Class XmlSerializer
'Usage
Dim instance As XmlSerializer

public class XmlSerializer
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 thus 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 run time. 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 run time, instances of the classes can be serialized into XML documents that follow the given schema. Likewise, these XML documents can be deserialized into run time objects. Note that the XML Schema is optional, and not required at design time or run time.

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 (www.w3.org) 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.

Public Class MyClass
    Public MyObjectProperty As MyObject
End Class

Public Class MyObject
    Public ObjectName As String
End Class

The serialized, XML output looks like this:

<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, you have two options. One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

Public Class PurchaseOrder
    <System.ComponentModel.DefaultValueAttribute ("2002")> _
    Public Year As String
End Class

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

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) in order 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:

System.Xml.Serialization.XmlSerializer(Type)

System.Xml.Serialization.XmlSerializer(Type,String)

If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, resulting in a memory leak and poor performance. The simplest solution is to use one of the two constructors above. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

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:

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.

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) 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("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 'PurchaseOrder


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


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 'Calculate
End Class 'OrderedItem


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 'Main
    
   Private Sub CreatePO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to serialize.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      Dim writer As New StreamWriter(filename)
      Dim po As New PurchaseOrder()
        
      ' Create 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()
        
      ' Create an OrderedItem object.
      Dim i1 As New OrderedItem()
      i1.ItemName = "Widget S"
      i1.Description = "Small widget"
      i1.UnitPrice = CDec(5.23)
      i1.Quantity = 3
      i1.Calculate()
        
      ' Insert the item into the array.
      Dim items(0) As OrderedItem
      items(0) = i1
      po.OrderedItems = items
      ' Calculate 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
      ' Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po)
      writer.Close()
   End Sub 'CreatePO
    
   Protected Sub ReadPO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify 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, handle 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
      ' Use the Deserialize method to restore the object's state with
      ' data from the XML document. 
      po = CType(serializer.Deserialize(fs), PurchaseOrder)
      ' Read the order date.
      Console.WriteLine(("OrderDate: " & po.OrderDate))
        
      ' Read the shipping address.
      Dim shipTo As Address = po.ShipTo
      ReadAddress(shipTo, "Ship To:")
      ' Read 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
      ' Read the subtotal, shipping cost, and total cost.
      Console.WriteLine(( New String(ControlChars.Tab, 5) & _
      " Subtotal"  & ControlChars.Tab & po.SubTotal))
      Console.WriteLine(New String(ControlChars.Tab, 5) & _
      " Shipping" & ControlChars.Tab & po.ShipCost )
      Console.WriteLine( New String(ControlChars.Tab, 5) & _
      " Total" &  New String(ControlChars.Tab, 2) & po.TotalCost)
    End Sub 'ReadPO
    
    Protected Sub ReadAddress(a As Address, label As String)
      ' Read the fields of the Address object.
      Console.WriteLine(label)
      Console.WriteLine(ControlChars.Tab & a.Name)
      Console.WriteLine(ControlChars.Tab & a.Line1)
      Console.WriteLine(ControlChars.Tab & a.City)
      Console.WriteLine(ControlChars.Tab & a.State)
      Console.WriteLine(ControlChars.Tab & a.Zip)
      Console.WriteLine()
    End Sub 'ReadAddress
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub 'serializer_UnknownNode
    
    
    Private 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

import System.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import System.IO.*;

/* 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. */
/** @attribute 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". */
    /** @attribute XmlArrayAttribute("Items")
     */
    public OrderedItem orderedItems[];
    public System.Decimal subTotal;
    public System.Decimal shipCost;
    public System.Decimal totalCost;
} //PurchaseOrder

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). */
    /** @attribute 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. */
    /** @attribute XmlElementAttribute(IsNullable = false)
     */
    public String city;
    public String state;
    public String zip;
} //Address

public class OrderedItem
{
    public String itemName;
    public String description;
    public System.Decimal unitPrice;
    public int quantity;
    public System.Decimal lineTotal;

    /* Calculate is a custom method that calculates the price per item,
       and stores the value in a field. */
    public void Calculate()
    {
        lineTotal = Decimal.Multiply(unitPrice, Convert.ToDecimal(quantity));
    } //Calculate
} //OrderedItem

public class Test
{
    public static void main(String[] args)
    {
        // Read and write purchase orders.
        Test t = new Test();
        t.CreatePO("po.xml");
        t.ReadPO("po.xml");
    } //main

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

        // Create 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";

        // Set ShipTo and BillTo to the same addressee.
        po.shipTo = billAddress;
        po.orderDate = System.DateTime.get_Now().ToLongDateString();

        // Create an OrderedItem object.
        OrderedItem i1 = new OrderedItem();
        i1.itemName = "Widget S";
        i1.description = "Small widget";
        i1.unitPrice = Convert.ToDecimal(5.23);
        i1.quantity = 3;
        i1.Calculate();

        // Insert the item into the array.
        OrderedItem items[] = { i1 };
        po.orderedItems = items;

        // Calculate the total cost.
        System.Decimal subTotal = new System.Decimal();
        for (int iCtr = 0; iCtr < items.length; iCtr++) {
            OrderedItem oi = items[iCtr];
            subTotal = Decimal.Add(subTotal, oi.lineTotal);
        }

        po.subTotal = subTotal;
        po.shipCost = Convert.ToDecimal(12.51);
        po.totalCost = Decimal.Add(po.subTotal, po.shipCost);

        // Serialize the purchase order, and close the TextWriter.
        serializer.Serialize(writer, po);
        writer.Close();
    } //CreatePO

    protected void ReadPO(String fileName)
    {
        // Create an instance of the XmlSerializer class;
        // specify the type of object to be deserialized.
        XmlSerializer serializer =
            new XmlSerializer(PurchaseOrder.class.ToType());
        /* If the XML document has been altered with unknown 
           nodes or attributes, handle them with the 
           UnknownNode and UnknownAttribute events.*/
        serializer.add_UnknownNode(
            new XmlNodeEventHandler(Serializer_UnknownNode));
        serializer.add_UnknownAttribute(
            new XmlAttributeEventHandler(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 = (PurchaseOrder)serializer.Deserialize(fs);

        // Read the order date.
        Console.WriteLine("OrderDate: " + po.orderDate);

        // Read the shipping address.
        Address shipTo = po.shipTo;
        ReadAddress(shipTo, "Ship To:");

        // Read the list of ordered items.
        OrderedItem items[] = po.orderedItems;
        Console.WriteLine("Items to be shipped:");
        for (int iCtr = 0; iCtr < items.length; iCtr++) {
            OrderedItem oi = items[iCtr];
            Console.WriteLine("\t" + oi.itemName + "\t"
                + oi.description + "\t" + oi.unitPrice + "\t"
                + oi.quantity + "\t" + oi.lineTotal);
        }
        // Read the subtotal, shipping cost, and total cost.
        Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.subTotal);
        Console.WriteLine("\t\t\t\t\t Shipping\t" + po.shipCost);
        Console.WriteLine("\t\t\t\t\t Total\t\t" + po.totalCost);
    } //ReadPO

    protected void ReadAddress(Address a, String label)
    {
        // Read the fields of the Address object.
        Console.WriteLine(label);
        Console.WriteLine("\t" + a.name);
        Console.WriteLine("\t" + a.line1);
        Console.WriteLine("\t" + a.city);
        Console.WriteLine("\t" + a.state);
        Console.WriteLine("\t" + a.zip);
        Console.WriteLine();
    } //ReadAddress

    private void Serializer_UnknownNode(Object sender, XmlNodeEventArgs e)
    {
        Console.WriteLine("Unknown Node:" + e.get_Name() + "\t" + e.get_Text());
    } //Serializer_UnknownNode

    private void Serializer_UnknownAttribute(Object sender,
        XmlAttributeEventArgs e)
    {
        System.Xml.XmlAttribute attr = e.get_Attr();
        Console.WriteLine("Unknown attribute " + attr.get_Name() + "='"
            + attr.get_Value() + "'");
    } //Serializer_UnknownAttribute
} //Test

System.Object
  System.Xml.Serialization.XmlSerializer

This type is safe for multithreaded operations.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft