Click here to Skip to main content
15,312,535 members
Articles / Programming Languages / XML
Posted 5 Jul 2003


503 bookmarked

Load and save objects to XML using serialization

Rate me:
Please Sign up or sign in to vote.
4.86/5 (126 votes)
1 Sep 2006CPOL7 min read
A C# program to demonstrate loading and saving an object to an XML file using XML serialization encapsulated in a wrapper class.

Demo form - Load-Save objects to XML



This C# program demonstrates loading and saving an object containing a bitmap and collections to an XML file using .NET XML serialization. XML serialization enables an object's public fields and properties to be saved and loaded to/from an XML file.

This article focuses on the C# 2.0 (Visual Studio 2005) implementation. The C# 1.1 code does not use Generics and static class declaration, because those features are only available in C# 2.0.


After discovering the usefulness of XML in storing data (including configuration settings for a program), I needed a solution to load and save an object's public fields and properties to/from an XML file without the complexity of navigating through the DOM (Document Object Model). I also wanted to provide an abstraction of the XML data as class objects, and only concern myself with the XML specifics when saving or loading data to/from a file. In addition, this 'load/save to XML' framework had to be reusable in other projects.

A practical solution - and the one demonstrated here - is to use the functionality provided by the .NET System.Xml.Serialization.XmlSerializer class encapsulated within a new class to provide loading and saving of an object to/from an XML file.

Using the code

File descriptions

  • Customer.cs - Class to be serialized to/from an XML file.
  • EmailAddress.cs - Class that stores an e-mail address for the Customer and is used as the object type for a collection of e-mail addresses.
  • ObjectXMLSerializer.cs - Class to encapsulate XML serialization, in XML document format (the default) or binary format.
  • MainForm.cs - Windows Form class that demonstrates loading and saving of the Customer object to the 'CustomerObject.xml' file.
  • CustomerObject.xml - File containing the serialized Customer object in the bin\Debug or \bin\Release folder (depending on your build configuration). This file is created when you press the Save button.

Enabling XML serialization of an object

Before we can serialize an object to XML, the object's class code must include various custom metadata attributes (e.g., [XmlAttributeAttribute(DataType="date")]) to tell the compiler that the class and its field and/or properties can be serialized. For example, in the Customer class:

// Set this 'Customer' class as the root node
// of any XML file its serialized to.
[XmlRootAttribute("Customer", Namespace="", IsNullable=false)]
public class Customer
    private Bitmap picture;

    /// <summary>
    /// Default constructor for this class
    /// (required for serialization).
    /// </summary>
    public Customer()

    // Set this 'DateTimeValue' field
    // to be an attribute of the root node.
    public System.DateTime DateTimeValue;

    // By NOT specifing any custom
    // Metadata Attributes, fields will be created
    // as an element by default.
    public int CustomerID;
    public string CustomerName;
    public int Age;

    // Set serialization to IGNORE
    // this field (ie. not add it to the XML).
    public bool CustomerPaid;

    // Set serialization to IGNORE this property
    // because the 'PictureByteArray' property
    // is used instead to serialize
    // the 'Picture' Bitmap as an array of bytes.
    public Bitmap Picture
        get { return picture; }
        set { picture = value; }

    // Serializes the 'Picture' Bitmap to XML.
    public byte[] PictureByteArray
            if (picture != null)
                TypeConverter BitmapConverter = 
                return (byte[]) 
                     BitmapConverter.ConvertTo(picture, typeof(byte[]));
                return null;
            if (value != null)
                picture = new Bitmap(new MemoryStream(value)); 
                picture = null; 

    // Serializes an ArrayList as a "Hobbies" array
    // of XML elements of type string named "Hobby".
    [XmlArray ("Hobbies"), XmlArrayItem("Hobby", typeof(string))]
    public System.Collections.ArrayList Hobbies = 
           new System.Collections.ArrayList();

    // Serializes an ArrayList as a "EmailAddresses" array
    // of XML elements of custom type EmailAddress named "EmailAddress".
    [XmlArray ("EmailAddresses"), 
     XmlArrayItem("EmailAddress", typeof(EmailAddress))]
    public System.Collections.ArrayList EmailAddresses = 
           new System.Collections.ArrayList();

Class to encapsulate XML serialization

The ObjectXMLSerializer class is used to encapsulate XML serialization, so that we can load and save an object regardless of its data type, with the help of Generics. Calling objects use the overloaded public methods, Load and Save.

The Load methods deserialize XML data from a previously serialized XML file into an object's public fields and properties.

The Save methods serialize an object's public fields and properties to an XML file.

Methods with the SerializedFormat parameter allow setting of the serialization format - either XML document format, or binary format. If no serialization format is specified, XML document formatting is used, by default.

The following private methods within ObjectXMLSerializer implement the core functionality for loading or saving data. Note that T is the placeholder for the generic type used to represent a serializable object:

private static T LoadFromBinaryFormat(string path, 
                 IsolatedStorageFile isolatedStorageFolder)
    T serializableObject = null;

    using (FileStream fileStream = 
           CreateFileStream(isolatedStorageFolder, path))
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        serializableObject = binaryFormatter.Deserialize(fileStream) as T;

    return serializableObject;

private static T LoadFromDocumentFormat(System.Type[] extraTypes, 
        string path, IsolatedStorageFile isolatedStorageFolder)
    T serializableObject = null;

    using (TextReader textReader = 
           CreateTextReader(isolatedStorageFolder, path))
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
        serializableObject = xmlSerializer.Deserialize(textReader) as T;


    return serializableObject;

private static void SaveToBinaryFormat(T serializableObject, 
        string path, IsolatedStorageFile isolatedStorageFolder)
    using (FileStream fileStream = 
           CreateFileStream(isolatedStorageFolder, path))
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(fileStream, serializableObject);

private static void SaveToDocumentFormat(T serializableObject, 
        System.Type[] extraTypes, string path, 
        IsolatedStorageFile isolatedStorageFolder)
    using (TextWriter textWriter = 
           CreateTextWriter(isolatedStorageFolder, path))
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
        xmlSerializer.Serialize(textWriter, serializableObject);

private static FileStream CreateFileStream(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
    FileStream fileStream = null;

    if (isolatedStorageFolder == null)
        fileStream = new FileStream(path, FileMode.OpenOrCreate);
        fileStream = new IsolatedStorageFileStream(path, 
                     FileMode.OpenOrCreate, isolatedStorageFolder);

    return fileStream;

private static TextReader CreateTextReader(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
    TextReader textReader = null;

    if (isolatedStorageFolder == null)
        textReader = new StreamReader(path);
        textReader = new StreamReader(new IsolatedStorageFileStream(path, 
                                  FileMode.Open, isolatedStorageFolder));

    return textReader;

private static TextWriter CreateTextWriter(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
    TextWriter textWriter = null;

    if (isolatedStorageFolder == null)
        textWriter = new StreamWriter(path);
        textWriter = new StreamWriter(new IsolatedStorageFileStream(path, 
                          FileMode.OpenOrCreate, isolatedStorageFolder));

    return textWriter;

private static XmlSerializer CreateXmlSerializer(System.Type[] extraTypes)
    Type ObjectType = typeof(T);

    XmlSerializer xmlSerializer = null;

    if (extraTypes != null)
        xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
        xmlSerializer = new XmlSerializer(ObjectType);

    return xmlSerializer;

Saving an object to an XML file

The following example code shows how to use the ObjectXMLSerializer class to save a Customer object to an XML file (in document format). We first build a Customer object from the values in the user interface, by calling our custom BuildCustomerFromForm method:

// Create customer object based on Form values.
Customer customer = this.CreateCustomer();

//Save customer object to XML file using our ObjectXMLSerializer class...
ObjectXMLSerializer<Customer>.Save(customer, XML_FILE_NAME);

Loading an object from an XML file

The following example code shows how to use the ObjectXMLSerializer class to load a Customer object from an XML file (in document format):

// Load the customer object from the XML file using our custom class...
customer = ObjectXMLSerializer<Customer>.Load(XML_FILE_NAME);

Points of interest

Storing a bitmap in an XML file

The Customer class includes a Picture property that stores a Bitmap object. Because a Bitmap cannot be automatically serialized/deserialized using the .NET System.Xml.Serialization.XmlSerializer class, the Bitmap object is saved to the XML file as an array of bytes, and converted back into a bitmap when the XML file is loaded.

Conversion from a Bitmap object to a byte array is achieved using the Bitmap object's System.ComponentModel.TypeConverter. Conversion from a byte array back to a Bitmap object is achieved using a System.IO.MemoryStream object supplied to the Bitmap object's constructor.

Note that two public properties are used to enable storing of the Bitmap: Picture and PictureByteArray. The Picture property is ignored during serialization (by using the XmlIgnoreAttribute attribute) because it's of type Bitmap. The value the Picture property gets or sets is stored in XML, during serialization, using the PictureByteArray property which performs the 'Bitmap to byte array' conversion (and vice-versa).

Storing a collection of strings in an XML file

The Customer class includes a Hobbies field that stores an ArrayList collection of strings. The attributes for the Hobbies field are as follows:

[XmlArray ("Hobbies"), XmlArrayItem("Hobby", typeof(string))]

The XML attribute, XmlArray, specifies the serialization of the Hobbies field as an array of XML elements named "Hobbies". The XML attribute, XmlArrayItem, defines the name of the array item as it will be stored in the XML file, as "Hobby", and its storage type as string. The following example shows how the array of Hobbies XML elements might appear in an XML file:



Storing a collection of custom objects in an XML file

The Customer class includes an EmailAddresses field that stores an ArrayList collection of custom EmailAddress objects. The attributes for the EmailAddresses field are defined similar to the Hobbies field.

Immediately before the class declaration, the XML attribute Serializable specifies that the EmailAddress class is serializable.

A default constructor with no parameters is included in the EmailAddress class as it is required for the .NET serialization.

The XML attribute XmlAttribute is specified for both fields of the EmailAddress class to demonstrate the usage of XML attributes. The following example shows how the array of EmailAddresses XML elements - with its fields stored as XML attributes - might appear in an XML file:


  <EmailAddress Address="" Destination="Business" />
  <EmailAddress Address="" Destination="Home" />
  <EmailAddress Address="" Destination="Other" />



Version 1.0

Original submission.

Version 2.0

  • Converted the solution to support .NET Framework 1.1.
  • Modified the ObjectXMLSerializer class to allow binary formatting of XML.
  • Added the Picture property to the Customer class to demonstrate storing a Bitmap object as XML.
  • Modified TestForm to include the above changes.

Version 2.1

  • Added the "Hobbies" collection to demonstrate storing a collection of strings as XML.
  • Added the "EmailAddresses" collection to demonstrate storing a collection of custom objects as XML.
  • Changed the use of 'property' to 'field', where appropriate (previous versions incorrectly used 'property' and 'field' synonymously).
  • Modified the C# project to include the above changes.

Version 3.0

  • Created a C# 2.0 implementation.
  • Changed the ObjectXMLSerializer class declaration (C# 2.0 only) and members from instance to static, because no data or behavior in the class depends on object identity.
  • Replaced the data type used as a serialized object with the use of generics, to provide strongly typed functionality (C# 2.0 only).
  • Refactored comments for clarity.
  • Corrected bugs in the commented examples.
  • Added overloaded methods to provide alternative access.
  • Changed the return type of Save methods to void instead of bool, because a file that cannot be saved will result in an exception.
  • Changed the case of parameters to camelCase to match the .NET Framework Design Guidelines.
  • Added using statements to objects that implement IDisposable to simplify object disposal.
  • Added additional private methods to encapsulate code.

Version 3.1

  • Removed extraneous object instantiation code for Load methods that remained after conversion from C# 1.1 to 2.0.
  • Removed demo version downloads for simplicity.
  • Renamed the SerializedFormats enum to SerializedFormat to match the .NET Framework Design Guidelines.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
New Zealand New Zealand
TC is a software developer with a Degree in Information Systems and commercial experience ranging from C DLL's to N-Tier Web applications.

Comments and Discussions

QuestionLicense Terms Used for code Pin
dbhatt7911-Mar-15 6:14
Memberdbhatt7911-Mar-15 6:14 
QuestionLicense Type used Pin
dbhatt7923-Feb-15 8:19
Memberdbhatt7923-Feb-15 8:19 
GeneralMy vote of 5 Pin
reachen22-Jul-13 20:34
Memberreachen22-Jul-13 20:34 
QuestionSerializer Listview (wpf application) Pin
alonetmr28-Jun-13 5:21
Memberalonetmr28-Jun-13 5:21 
AnswerRe: Serializer Listview (wpf application) Pin
leiyangge4-Jan-14 23:05
Memberleiyangge4-Jan-14 23:05 
GeneralThis is very good article. Pin
Jayesh Sorathia14-Sep-12 22:42
MemberJayesh Sorathia14-Sep-12 22:42 
QuestionUsing a class and class Data to Genereate XML Pin
cpquest2-Apr-12 17:36
Membercpquest2-Apr-12 17:36 
GeneralMy vote of 5 Pin
Shahin Khorshidnia4-Jan-12 2:57
professionalShahin Khorshidnia4-Jan-12 2:57 
GeneralMy vote of 5 Pin
aalhanane8-Dec-11 10:55
Memberaalhanane8-Dec-11 10:55 
QuestionMay I use your class in my project? Pin
grogilius7-Nov-11 8:10
Membergrogilius7-Nov-11 8:10 
AnswerRe: May I use your class in my project? Pin
T-C8-Nov-11 12:26
MemberT-C8-Nov-11 12:26 
GeneralThanks! Pin
grogilius8-Nov-11 21:20
Membergrogilius8-Nov-11 21:20 
Questionsave function question? Pin
jobo2323-Oct-11 20:59
Memberjobo2323-Oct-11 20:59 
GeneralMy vote of 5 Pin
jobo2323-Oct-11 20:35
Memberjobo2323-Oct-11 20:35 
GeneralMy vote of 5 Pin
John-ph10-Aug-11 22:45
MemberJohn-ph10-Aug-11 22:45 
QuestionSerialize class in a xml (string) instead of a file Pin
LeonardoX2230-Jul-11 13:37
MemberLeonardoX2230-Jul-11 13:37 
GeneralMy vote of 5 Pin
Sniper At Work16-Feb-11 2:33
professionalSniper At Work16-Feb-11 2:33 
GeneralMy vote of 5 Pin
Azagatoth5-Aug-10 8:19
MemberAzagatoth5-Aug-10 8:19 
GeneralMy vote of 5 Pin
Dimps7-Jul-10 4:38
MemberDimps7-Jul-10 4:38 
Generalspecial characters Pin
oliver.hawk20-May-09 2:54
Memberoliver.hawk20-May-09 2:54 
GeneralSerialization question. Pin
irina-z20-Apr-09 6:33
Memberirina-z20-Apr-09 6:33 
GeneralGreat Example / VB Pin
marchesb4-Sep-08 5:47
Membermarchesb4-Sep-08 5:47 
Generalserialization to App.config Pin
PetoG3-Sep-08 22:22
MemberPetoG3-Sep-08 22:22 
GeneralBe careful with FileMode.OpenOrCreate.. Pin
st1413-Aug-08 15:56
Memberst1413-Aug-08 15:56 
QuestionWhy Static ? Pin
vertex8520-May-08 0:10
Membervertex8520-May-08 0:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.