Control serialization and deserialization in C#


[example]

For information on basic serialization and deserialization, see Serialize and deserialize objects in C#.

By placing attributes on a class’s properties, you can control how those properties are serialized. The following code shows a Person class that demonstrates several XML attributes. You might want to refer to the results at the end to see how each attribute affects the serialization.

[Serializable()]
public class Person
{
    [XmlAttributeAttribute("GivenName")]
    public string FirstName;
    [XmlAttributeAttribute("FamilyName")]
    public string LastName;
    [XmlElement("StreetAddress")]
    public string Street;

    public enum ContactMethods
    {
        [XmlEnum("SnailMail")]
        Post,
        [XmlEnum("Telephone")]
        Phone,
        [XmlEnum("Email")]
        Email
    }

    [XmlElement("ContactMethod")]
    public ContactMethods PreferredMethod;

    public string City;
    public string State;

    [XmlIgnore()]
    public string Zip;

    [XmlArray("PhoneNumbers"), XmlArrayItem("PhoneNum")]
    public string[] Phones = new string[1];

    [XmlArray("EmailAddresses")]
    public string[] Emails = new string[1];

    // Empty constructor required for serialization.
    public Person()
    {
    }

    // Initializing constructor.
    public Person(string first_name, string last_name,
        string street, string city, string state, string zip,
        string phone1, string phone2, string email1,
        string email2, ContactMethods contact_method)
    {
        FirstName = first_name;
        LastName = last_name;
        Street = street;
        City = city;
        State = state;
        Zip = zip;
        Phones = new string[] { phone1, phone2 };
        Emails = new string[] { email1, email2 };
        PreferredMethod = contact_method;
    }
}

The following list describes the attributes used by the Person class.

  • XmlAttributeAttribute – Tells the serializer to make the property an attribute of the class rather than a separate element. It also gives the name that the attribute should have in the resulting XML. In this example, the FirstName property is saved as the GivenName attribute and the LastName property is saved as the FamilyName attribute.
  • XmlElement – Explicitly says that a property should be serialized as an element (the default) and can give the element a new name. In this example, the Street property is saved with the element name StreetAddress.
  • XmlEnum – Enumerated values are saved as textual representations. The XmlEnum attributes changes the name used for an enumerated value. For example, this program’s code uses the enumerated ContactMethods values Post, Phone, and Email. The XML serialization calls those values SnailMail, Telephone, and Email.
  • XmlIgnore – This tells the serializer to not serialize or deserialize a property. This is useful for values that are created on the fly (such as the time or date the code did something), for properties that are duplicates of other properties (if the object has temperature properties for both Centigrade and Fahrenheit, you don’t need to store both), and for properties that are other objects that are not serializable.
  • XmlArray – This tells the serializer what name to give an array property.
  • XmlArrayItem – This tells the serializer what name to give a value inside an array property. If you don’t include this, the items are named after their data types. In this example, the items in the EmailAddresses array are named “string.”

The following text shows a serialized Person. Note the results produced by the Person class’s serialization attributes. Notice that the Zip property, marked with XmlIgnore, is nowhere to be found.

<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  GivenName="Mickey" FamilyName="Moose">
  <StreetAddress>1337 Leet St</StreetAddress>
  <ContactMethod>Email</ContactMethod>
  <City>Bugsville</City>
  <State>CA</State>
  <PhoneNumbers>
    <PhoneNum>987-654-3210</PhoneNum>
    <PhoneNum>999-888-7777</PhoneNum>
  </PhoneNumbers>
  <EmailAddresses>
    <string>email1@nowhere.com</string>
    <string>email2@nowhere.com</string>
  </EmailAddresses>
</Person>

Download the example and see the earlier example for more details about the actual serialization and deserialization processes.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, serialization and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *