Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Serialization
 How to: Serialize an Object

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
.NET Framework Developer's Guide 
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.

NoteNote

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.

    Visual Basic
    Dim myObject As MySerializableClass = New MySerializableClass()
    ' Insert code to set properties and fields of the object.
    Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass))
    ' To write to a file, create a StreamWriter object.
    Dim myWriter As StreamWriter = New StreamWriter("myFileName.xml")
    mySerializer.Serialize(myWriter, myObject)
    myWriter.Close()
    

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

See Also

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Consider making XmlSerializer instances 'static'      Dave Black   |   Edit   |   Show History
When using an XmlSerializer for types known at design-time, create a static instance of an XmlSerializer for the known type. This can drastically improve performance.
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker