How do you use XMLSerialize for Enum typed properties in c#?

Rhubarb picture Rhubarb · Feb 21, 2010 · Viewed 28.7k times · Source

I have a simple enum:

enum simple 
{ 
  one, 
  two, 
  three 
};

I also have a class that has a property of type simple. I tried decorating it with the attribute: [XmlAttribute(DataType = "int")]. However, it fails when I try to serialize it using an XmlWriter.

What is the proper way to do this? Do I have to mark the enum itself as well as the property, and if so, with which data type?

Answer

zebrabox picture zebrabox · Feb 21, 2010

As per Darin Dimitrov's answer - only extra thing I'd point out is that if you want control over how your enum fields are serialized out then you can decorate each field with the XmlEnum attribute.

public enum Simple
{
      [XmlEnum(Name="First")]
      one,
      [XmlEnum(Name="Second")]
      two,
      [XmlEnum(Name="Third")]
      three,
}