How to: Serialize an Object


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.

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

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

Introducing XML Serialization
How to: Deserialize an Object