Deserializing to an enum

I have an application where I deserialize an xml stream from a third party. One of the fields is a task code which can be one of only three values, insert, update and delete. This is an obvious candidate for an enum.

public enum TaskCode
{
    Delete,
    Insert,
    Update
}

This is looks good but relies on the xml stream using the same capitalization as shown above, however my incoming xml stream used all caps. I could have changed my enums to all caps, but I’d end up with some ugly lines of code.

Fortunately the XmlEnum attribute solves this problem.

public enum TaskCode
{
    [XmlEnum("DELETE")] Delete,
    [XmlEnum("INSERT")] Insert,
    [XmlEnum("UPDATE")] Update
}

See http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlenumattribute.aspx for more.

Leave a Reply

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