Ignore a property during xml serialization but not during deserialization

This is the solution outlined by Manoj:

If you want to suppress serialization of a specific property Foo, but still be able to deserialize it, you can add a method public bool ShouldSerializeFoo() that always returns false.

Example:

public class Circle2
{
    public double Diameter { get; set; }
    public double Radius { get { return Diameter / 2; } set { Diameter = value*2; } }

    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public bool ShouldSerializeRadius() {return false;}
}

This will cause the Radius to not be serialized, but still allow it to be deserialized.

This method has to be public for the XMLSerializer to find it, so in order to avoid polluting the namespace you can add the EditorBrowsable attribute to hide it from the IDE. Unfortunately this hiding only works if the assembly is referenced as a DLL in your current project, but not if you edit the actual project with this code.

Leave a Comment