views:

18

answers:

1

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.

+1  A: 

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; }
}
MonkeyWrench
Double `XmlElements` only works to supply an `XmlChoiceIdentifier`. Writing all this code myself is somewhat of a last resort, I cán solve it too with `UnknownElement` but it gets hacky.
Jan Jongboom