Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerialize an Enum Flag field

I have this :

    [Flags]
    public enum InfoAbonne{civilite,name,firstname,email,adress,country }

    public class Formulaire
    {
      private InfoAbonne _infoAbonne{ get; set;}
      public Formulaire()
      {}
    }

I want to Xml serialize Formulaire

If I init :
_infoAbonne = InfoAbonne.name | InfoAbonne.email;

In my Xml Result I get only :

<InfoAbonne>email</InfoAbonne>
like image 689
Christophe Debove Avatar asked Jan 23 '12 11:01

Christophe Debove


2 Answers

Even though you added the Flags attribute to your enum, you still need to make sure that the values are powers of two:

[Flags]
public enum InfoAbonne
{
    civilite = 1,
    name = 2,
    firstname = 4,
    email = 8,
    adress = 16,
    country = 32
}

See the guidelines laid out in the Remarks section of the documentation.

like image 93
Daniel Hilgarth Avatar answered Sep 28 '22 04:09

Daniel Hilgarth


The basic idea with these sorts of problems is to serialize a backing field which mimics the field you want to serialize. Same principle can be applied to complex types such as Bitmaps etc... For instance, instead of serializing the Enum field directly, you could serialize a backing field of type int:

// Disclaimer: Untested code, both in execution and compilation
[Flags]      
public enum InfoAbonne 
{
    civilite = 0x1, // Increment each flag value by *2 so they dont conflict
    Name=0x2,
    firstname=0x4,
    email=0x8,
    adress=0x10,
    country=0x20 
}  

// Don't serialize this property
[XmlIgnore]
private InfoAbonne _infoAbonne { get; set;} 

// Instead serialize this property as integer
// e.g. name | email will equal 0xA in hex, or 10 in dec
[XmlElement("InfoAbonne")]
public int InfoAbonneSerializer 
{ 
    get { return (int)_infoAbonne; } 
    set { _infoAbonne= (InfoAbonne) value; } 
} 

Best regards,

like image 45
Dr. Andrew Burnett-Thompson Avatar answered Sep 28 '22 04:09

Dr. Andrew Burnett-Thompson