Pierre Greborio.NET

Talking about .NET world

XML Serialization and enums

Well, I was looking what ASP.NET web services generates when I have an enum parameter. Consider the following type:

public enum MyEnum : int
{
  EnumValue1 = 0,
  EnumValue2 = 2
}

I'm expecting something like

<xs:simpleType name="MyEnum">
 <xs:restriction base="xs:int">
  <xs:enumeration value="0" />
  <xs:enumeration value="2" />
 </xs:restriction>
</xs:simpleType>

But the xsd produces:

<xs:simpleType name="MyEnum">
 <xs:restriction base="xs:string">
  <xs:enumeration value="EnumValue1" />
  <xs:enumeration value="EnumValue2" />
 </xs:restriction>
</xs:simpleType>

Even if I'm decorating the enum values with System.Xml.Serialization.XmlEnumAttribute I can't get back an XML schema with a restriction of int instead of string. Why DataType of XmlElementAttribute doesn't work from primitives ? I don't know, but today I have to edit the WSDL manually.

 

Posted: Jan 09 2004, 06:04 PM by PierreG | with 2 comment(s)
Filed under:

Comments

Richard Norman said:

You know when I think about it, maybe that is the way it is supposed to work. I mean through the webservice if you were sending an int, then it would keep it as such. BUt if you are sending an ENUM type that is then interpeted by the receiving system, then you want the enumerated value sent across as a string.

SO in this example you are sending MyEnum.EnumValue1. "EnumValue1" is a string until the type is interpeted at the web service as a 0 (or whatever value it is).

If you were passing it as an int, then you need to define the Enumeration on the client/Sender's side before is is sent cause the type "EnumValue1" means nothing to the receiver.

Just a thought in reasoning... I am sure someone will correct me if I am wrong.
# January 9, 2004 1:23 PM

Pierre Greborio said:

The problem is on validation data validation. Consider the followinf web method:

[WebMethod]
public string PrintEnum(MyEnum e)
{
return e.ToString();
}

if you send to the method 0 you'll get back EnumValue1 as expected. If you send 1 you'll get back 1 ! Even if 1 is not part of the enum.
# January 10, 2004 4:45 PM