deserialize enum value as int

S

slamb

Hi all,
Does anyone know of a way to deserialize xml data that has an element
that represents an enum value but is actually an int?

I know I can use [XmlEnum(Name="23")] to tag enum values, that works
but is too messy. I have many enums and tagging all values would not
be good.


xml data
<Top>
<Element>23</Element>
</Top>

c# code
public enum SomeEnumType
{
Value1 = 23,
Value2 = 15
}

public class Top
{
SomeEnumType Element;
}

SomeEnumType Deserialize(Stream stream)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Top));
object obj = xmlSerializer.Deserialize(stream);
Top top = obj as Top;
if (top == null)
throw new SomeException();

return top.Element;
}
 
G

Guest

Hi Slamb,
if you want to get an enum value from an integral type you have in your
XML, you can use Enum.Parse. For example:

enum MyNameEnum
{
Fred = 1,
Bob = 2,
George = 3
}

int intNumber = 2;
MyNameEnum nme = (MyNameEnum)Enum.Parse(typeof(MyNameEnum),
intNumber.ToString());


When doing the above it is also a good idea to check that the value you are
trying to convert to an enum entry is valid, you can do this by calling:

if(!Enum.IsDefined(typeof(MyNameEnum), intNumber))
{
//throw exception
}
else
{
//keep going with your processing
}

Use this call sparingly though, I believe it is quite an expensive call to
perform.


Hope that helps
Mark R Dawson
 
S

slamb

That works for converting a single int to an enum value. However, I
really would like the serialization process to take care of this detail
via a hook or an attribute or something else. I have many different
sets of data that include different enum types. Writing code to
convert individual variables is not a clean solution.

The problem is that the call to Deserialize will throw an exception
when it sees 23 instead of Value1, or in the example Mark posted, 3
instead of George.

Thanks though.
 
S

slamb

That works for converting a single int to an enum value. However, I
really would like the serialization process to take care of this detail
via a hook or an attribute or something else. I have many different
sets of data that include different enum types. Writing code to
convert individual variables is not a clean solution.

The problem is that the call to Deserialize will throw an exception
when it sees 23 instead of Value1, or in the example Mark posted, 3
instead of George.

Thanks though.
 

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