newbie_86
newbie_86

Reputation: 4610

serialise to xml

I have a class and I need to serialize it to XML, but only specific properties i.e. not all. What's the best way to do this? The alternative is to create a dictionary of the properties and their values and then serialize the dictionary.

Upvotes: 0

Views: 114

Answers (2)

LightStriker
LightStriker

Reputation: 21004

The above answer works well. But I didn't like the idea of everything being serialized and only specified field not being. Just a case of different preference, really, I like to control how things work.

Using ISerializable, which from MS is : "Allows an object to control its own serialization and deserialization." and some reflection:

    // Required by ISerializable
    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        FieldInfo[] fields = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (FieldInfo field in fields)
        {
            if (!IsSerializable(field))
                continue;

            info.AddValue(field.Name, field.GetValue(this));
        }
    }

    protected bool IsSerializable(FieldInfo info)
    {
        object[] attributes = info.GetCustomAttributes(typeof(SerializableProperty), false);

        if (attributes.Length == 0)
            return false;

        return true;
    }

"SerializableProperty" is an empty Attribute I put on fields I want to serialize.

As for which serializer, it is totally up to you. XML is nice because you can read and edit it after. However, I went with the BinaryFormatter, which gives smaller file size in case of complex or large structure.

Upvotes: 0

Michal Klouda
Michal Klouda

Reputation: 14521

Have a look at XmlAttributes.XmlIgnore Property. All you need to do is decorating fields you don't want to serialize with [XmlIgnoreAttribute()]

Sample class:

// This is the class that will be serialized.  
public class Group
{
   // The GroupName value will be serialized--unless it's overridden. 
   public string GroupName;

   /* This field will be ignored when serialized--unless it's overridden. */
   [XmlIgnoreAttribute]
   public string Comment;
}

Upvotes: 3

Related Questions