How do I serialize an enum value as an int?
Posted
by Espo
on Stack Overflow
See other posts from Stack Overflow
or by Espo
Published on 2009-02-03T08:40:28Z
Indexed on
2010/03/16
6:46 UTC
Read the original article
Hit count: 280
I want to serialize my enum-value as an int, but i only get the name.
Here is my (sample) class and enum:
public class Request {
public RequestType request;
}
public enum RequestType
{
Booking = 1,
Confirmation = 2,
PreBooking = 4,
PreBookingConfirmation = 5,
BookingStatus = 6
}
And the code (just to be sure i'm not doing it wrong)
Request req = new Request();
req.request = RequestType.Confirmation;
XmlSerializer xml = new XmlSerializer(req.GetType());
StringWriter writer = new StringWriter();
xml.Serialize(writer, req);
textBox1.Text = writer.ToString();
This answer (to another question) seems to indicate that enums should serialize to ints as default, but it doesn't seem to do that. Here is my output:
<?xml version="1.0" encoding="utf-16"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<request>Confirmation</request>
</Request>
I have been able to serialize as the value by putting an "[XmlEnum("X")]" attribute on every value, but this just seems wrong.
© Stack Overflow or respective owner