Jan Jongboom
Jan Jongboom

Reputation: 27322

Change class signature, process old xml serialized instances

Let's assume I have got a class like:

public class SomeObject
{
    public Guid InternalId { get; set; }
    public string Address { get; set; }
}

I store instances of this object into the ASP.NET profile. It get's XML serialized and everything is fine. Now I want to reduce the size of the profile, and I want to replace the long propertynames by something shorter:

public class SomeObject
{
    [XmlElement("id")]
    public Guid InternalId { get; set; }
    [XmlElement("ad")]
    public string Address { get; set; }
}

New objects get serialized just fine, and short, and everything. However: the XmlSerializer cannot deserialize the old XML files. Is there any hook I can apply to change a classes signature, but still be able to deserialize old instances.

I have the eventhandler XmlSerializer_UnknownElement, and then I can set the value of the target property myself, however I only have the value of the element as a string, so I should parse it by myself which is quite error-prone.

Upvotes: 0

Views: 376

Answers (1)

MonkeyWrench
MonkeyWrench

Reputation: 1839

Two answers, one I know will work, the other I'm not sure.

1) Implement the IXmlSerializable interface in your class. Its very easy to do, and gives you complete control over how the class is serialized and deserialized.

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

2) Not sure if this will work, but try adding another XmlElementAttribute tag to your class properties. It compiles, but I'm not sure if it'll work.

public class SomeObject
{
    [XmlElement("InternalId")]
    [XmlElement("id")]
    public Guid InternalId { get; set; }
    [XmlElement("Address")]
    [XmlElement("ad")]
    public string Address { get; set; }
}

Upvotes: 1

Related Questions