views:

196

answers:

2

I have simple enum, enum simple { one, two, three }, and I have a class that has a property of type simple. I tried decorating it with the attribute: [XmlAttribute(DataType = "int")], but when I try to serialize it using an XmlWriter, it fails. 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?

+4  A: 

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"&gt;
    <Simple>three</Simple>
</Foo>
Darin Dimitrov
That works but it makes the enum property an element not an attribute. When I try to make it an attribute it fails. Any suggestions?
Rhubarb
Try decorating the property with XmlAttribute: `[XmlAttribute("simple")]public Simple Simple { get; set; }`
Darin Dimitrov
Properties don't seem able to be decorated. Fields only, correct?
Rhubarb
+2  A: 

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