Rhubarb
Rhubarb

Reputation: 4003

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

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?

Upvotes: 32

Views: 38806

Answers (2)

zebrabox
zebrabox

Reputation: 5764

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,
}

Upvotes: 56

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

There shouldn't be any problems serializing enum properties:

public enum Simple { one, two, three }

public class Foo
{
    public Simple Simple { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var writer = XmlWriter.Create(Console.OpenStandardOutput()))
        {
            var foo = new Foo
            {
                Simple = Simple.three
            };
            var serializer = new XmlSerializer(foo.GetType());
            serializer.Serialize(writer, foo);
        }
    }
}

produces:

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Simple>three</Simple>
</Foo>

Upvotes: 24

Related Questions