Search code examples
c#.netxmlxsd

Converting xsd enums to C#


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?


Solution

  • 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.