Serialize an Enum using the Enum names and not value

C

Chris Dunaway

Suppose I have the following enum:

public enum MyEnum {
EnumVal1 = 1,
EnumVal2 = 2,
EnumVal3 = 3
}

I want to serialize the enum but I want the /names/ of the enum to be
stored in the .xml file, like this:

MyEnum e;
e = MyEnum.EnumVal2;

// Serialization code here


I want the resulting element or attribute to be like this:

<myenum>EnumVal2</myenum>

Can this be done? Can you control how an enum is serialized?

Thanks,
 
N

Nicholas Paldino [.NET/C# MVP]

Chris,

While you can't control how the enumeration is serialized, you can
control how your class is serialized (I'm assuming you are using XML
Serialization).

You can implement the IXmlSerializable interface, and handle the
serialization yourself.

You can also expose the property exposing the enum as a string, and
return the string value representing the name of the enumeration when the
property is fetched.

You might also want to look at the documentation for the
XmlEnumAttribute class, as it will allow you to change how an enumeration is
serialized by the XmlSerializer.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top