C# Serialize an object to/from XML

There have been many times I've needed to serialize an object to/from XML. .NET makes this incredibly easy. With a few meta tags your class(es) can easily be serialized and deserialized. You can then take this even further any start applying custom attributes to have as much granular control over the serialization as you want.

For instance lets' take a very basic class with some data and properties.

public class Person
{
    int _age;
    String _name;

    /// Gets or sets the Age of the person.
    public int Age
    {
       get { return _age; }
       set { _age = value; }
    }

    /// Gets or sets the Name of the person.
    public String Name
    {
       get { return _name; }
       set { _name = value; }
    }

    /// Creates a new instance of the Person class
    public Person()
    {
    }

}
Now let's take this class and add the [Serializable] attribute.

[Serializable]
public class Person
{
    int _age;
    String _name;

    /// Gets or sets the Age of the person.
    public int Age
    {
       get { return _age; }
       set { _age = value; }
    }

    /// Gets or sets the Name of the person.
    public String Name
    {
       get { return _name; }
       set { _name = value; }
    }

    /// Creates a new instance of the Person class
    public Person()
    {
    }

}

You can now take this class to/from XML. When you serialize it the .net parser will look at all public properties and fields and convert them to XML.

You will end up with XML that will look like the following:

<xml version="1.0" />
<Person>
<Age>X</Age>
<Name>Y</Age>
</Person>

Whatever values you have stored in the name and age fields will be written to the XML.

Obviously this is a very primitive example of what you can do to get your classes into XML. There are a wide variety of XML Attributes you can apply to your classes to more fully control the serialization. This is a basic example of how to get your class into and back from XML.

A quite note on data types. All the .net value types (int, String, etc) can be converted to XML; however some of the more complex reference types (classes) may not be convertible. Be careful when serializing all your properties, etc fully support serialization.

Comments

Popular Posts