Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / XML

XML Serializer Library

Rate me:
Please Sign up or sign in to vote.
4.92/5 (12 votes)
10 Dec 2007CPOL4 min read 60.3K   1.8K   66   4
A library for serializing any class in XML format.
Screenshot - XmlSerializer.JPG

Introduction

The goal of my Serializer is the serialization of objects in XML format.

.NET Framework has some serializers just like soap and binary, but with them the user does not have full control during serialization.

Another tool to serialize objects is .NET XmlSerializer. In this case, the user has more control, but there are some limitations:

  • It is possible to serialize public properties only.
  • It is not possible to serialize private or protected fields.

This library allows to serialize fields and properties with any modifiers.

What You See in the Program Tester

At the left side of the program, at the top, you see the classes used for testing the library, while at the bottom, some information is shown about the selected class.

In the center of the program, you can see a PropertyGrid control that visualizes data for the selected class that will be serialized. The serialization (and deserialization) is made through the SerializableData class.

At the right of the program, you can see the XML file that is generated if you save (or load) an instance of a class.

Using the Code

A simple example of serialization is shown here. A Person class has a first name, a second name and an age. A Student derives from Person:

C#
[XmlClassSerializable("person")]
public class Person
{
    public Person()
    {
    }

    string _firstName = string.Empty;
    [XmlFieldSerializable("firstName")]
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    string _lastName = string.Empty;
    [XmlFieldSerializable("lastName")]
    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    [XmlFieldSerializable("age")]
    int _age = 0;
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

...

[XmlClassSerializable("student", false)]
public class Student : Person
{
    public Student()
    {
    }

    [XmlFieldSerializable("subject")]
    string _subject = string.Empty;
    public string Subject
    {
        get { return _subject; }
        set { _subject = value; }
    }
}

A custom class to serialize must have the XmlClassSerializable attribute with a name that will represent the tag name in the XML file. The fields or properties to serialize must have the XmlFieldSerializable attribute with a name that will represent the tag name in the XML file. If you don't insert any name, the XML tag will have the name of the class type or the name of the field. The properties are serializable if they have set and get functions (also protected or private).

The class Student has the XmlClassSerializable with two parameters, the name of the tag in the XML file and a second parameter that indicates if you want to serialize the fields in the entire hierarchy. If you set it to true (or you don't specify anything), you will serialize the subject and also the first name, last name and age, otherwise you will serialize the subject only. A third parameter, BindingFlags, can be specified so you have full control during serialization of fields.

Now, it is necessary to instantiate the serializer to store the object:

C#
Serializer serializer = new Serializer();

try
{
    serializer.Serialize(_fileName, _person);
}
catch (XmlSerializationException xmlException)
{
    MessageBox.Show(xmlException.Message);
}

To load the stored object:

C#
Serializer serializer = new Serializer();

try
{
    _person = serializer.Deserialize(_fileName) as Person;
}
catch (XmlSerializationException xmlException)
{
    MessageBox.Show(xmlException.Message);
}

The serializer throws an exception (XmlSerializationException) if errors occur. For example, if you mark a field with an XmlFieldSerializable attribute, but the field is constant, the serializer will generate an error. Another case is when you serialize a property without set and get functions.

For a more complex example using this library, you can download the code here.

Main Schemes

  • Orange color describes a hot spot class (interface or abstract class usually)
  • Yellow color describes active classes
  • Blue color describes passive classes (data containers or structs usually)
  • Light grey color describes classes of the framework that are not important in the current scheme
  • Dark grey color describes classes external to framework

This scheme represents the serializer scheme with main components:

Screenshot - XmlSerializer2.JPG

This scheme represents all components that manage the SerializableData class used to transform XML in objects and vice versa:

Screenshot - XmlSerializer3.JPG

This scheme represents custom attributes to mark serializable classes and fields:

Screenshot - XmlSerializer4.JPG

Specifications

At the moment, types that can be serialized are:

  • Custom classes that derive from serializable classes or not
  • Classes that derive from the ICollection interface. I test the library (as you see in the program tester) with classes derived from generic List, generic Collection and ArrayList
  • Any field of a base type (just like int, float, etc.)
  • Fields of System.Array type
  • struct

In some cases, it is convenient (and necessary) to specify the BindingFlags to serialize an object, otherwise the entire hierarchy will be serialized.

I did not test this library very well. For any problems or if you find bugs, please refer them to me.

Problems

  • Performances during deserialization, caused by an intensive use of Reflection

Future Developments

  • A C++ .NET 2005 version
  • Refactoring of some parts

References

For documentation:

For object-oriented and color theory and a lot of software development information:

License

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


Written By
Software Developer
Italy Italy
I am a biomedical engineer. I work in Genoa as software developer. I developed MFC ActiveX controls for industrial automation for 2 years and packages for Visual Studio 2005 for 1 year. Currently I'm working in .NET 3.5 in biomedical area.

Comments and Discussions

 
GeneralPraise Pin
henry_ye9-Apr-19 17:38
henry_ye9-Apr-19 17:38 
Questionhashtables and sortedlists Pin
Laurent_VP20-Dec-06 22:50
Laurent_VP20-Dec-06 22:50 
AnswerRe: hashtables and sortedlists Pin
jonnynolimits21-Dec-06 21:33
jonnynolimits21-Dec-06 21:33 
GeneralExcellent work Pin
Francesco Pratolongo24-Oct-06 3:19
Francesco Pratolongo24-Oct-06 3:19 
Very good work, well coded and documented.
I think it's a very usefull library and quite easy to be used.

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.