Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 853
Rhubarb Avatar asked Feb 21 '10 15:02

Rhubarb


2 Answers

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, } 
like image 108
zebrabox Avatar answered Sep 28 '22 23:09

zebrabox


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> 
like image 26
Darin Dimitrov Avatar answered Sep 28 '22 21:09

Darin Dimitrov