Need a way to do XML serialization of enum to/from int without XmlEnum attribute RRS feed

  • Question

  • I have a need to do XML serialization of an enum so that the integer value of the enum is serialized and deserialized as its integer value. By default, enums are serialized as their value name representation.  Since the enum is in an assembly that I am using, I cannot use XmlEnum attribute to provide the XML conversion since I don't have a means to alter the original enum definition. 

    I have seen some articles that offer a means to use XmlIgnore attribute on an enum object instance and then use an XmlElement on an integer property that converts to/from the enum, but that seems like a clunky solution that requires exposing another property in the class that represents the enum as an int.

    Instead, I noticed that the XmlElement attribute has a Type and DataType property that can be set.  I tried using this on my enum property hoping it would convert the enum to/from int, but instead I get an InvalidOperationException when I try to serialize ("The type for XmlElement may not be specified for primitive types."). 

    Sample snippet:

    public class MyClass
    [XmlElement(Type = typeof(int), DataType = "int")]       
    public Destination_e Destination { get; set; }

    public string Title {get; set;}

    Is there a cleaner way that I can serialize my enumerator property so that it converts to/from int rather than serialize it as the string representation of the enum value name?  I hate to have to exhort to using a custom IXmlSerializable implementation to do something this trivial that should be handled by the XmlElement attribute.

    Friday, June 8, 2018 1:42 PM