I have an xsd file from which I am generating a C# class. In order to provide easier maintenance, I'd like to define an enumeration within the xsd file only so that when I have to change the enum, I only have to update it in one place. I know how to create the enum, but when the C# code is generated, I need the enum members to have custom values, so the result would be similar to:
public enum SetupTypeEnum {
None = 0,
NewInstall = 1,
Modify = 2,
Upgrade = 4,
Uninstall = 8
}
Is there any way to write the xsd to accomplish this?
You can add annotations specific for code generation (this only works for svcutil, not for xsd.exe) to your xsd file. The xsd definition for your enum would be something like this:
<xs:simpleType name="SetupTypeEnum">
<xs:restriction base="xs:string">
<xs:enumeration value="None">
<xs:annotation>
<xs:appinfo>
<EnumerationValue xmlns="http://schemas.microsoft.com/2003/10/Serialization/">0</EnumerationValue>
</xs:appinfo>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="NewInstall">
<xs:annotation>
<xs:appinfo>
<EnumerationValue xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1</EnumerationValue>
</xs:appinfo>
</xs:annotation>
</xs:enumeration>
...
</xs:restriction>
</xs:simpleType>
These annotations allow you to explicitly define the numerical value of each enum value. You can find an example on this msdn page if you search for "EnumerationValue".
Update: John Saunders correctly states in his comment that this doesn't work if you use xsd.exe. However, if you use svcutil.exe to create the C# code, then the annotations will work.
Example of using svcutil.exe
:
svcutil /dconly "D:\test.xsd" /o:"D:\test.cs"
If you use svcutil
instead of xsd.exe
, then the generated code will by slightly different. The most important difference is that svcutil
will generate attributes for DataContractSerialization instead of XmlSerialization.
The concept of "enumeration" in XSD has nothing to do with the concept of "enum" in C#.
"enumeration" in XML Schema is a way of restricting the possible lexical values of a type to an enumerated list of values. For instance:
<xs:simpleType name="SummerMonth">
<xs:restriction base="xs:gMonth">
<xs:enumeration value="--07"/>
<xs:enumeration value="--08"/>
<xs:enumeration value="--09"/>
</xs:restriction>
</xs:simpleType>
This type restricts the value space to the set of "Summer" months (July, August and September).
Clearly, this has no correspondence to a "enum" in C# or any other programming language I know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With