在xsd中指定枚举元素的值

时间:2013-10-24 13:28:35

标签: c# xml xsd

我希望我的枚举类具有名称 - 值对。我必须在我的xsd中定义枚举。

例如: 目前我的xsd为

    <xsd:simpleType name="ColorCode">
       <xsd:restriction base="xsd:string">
       <xsd:enumeration value="Red"/>
       <xsd:enumeration value="Orange"/>
       <xsd:enumeration value="LightGreen"/>
       <xsd:enumeration value="DarkGreen"/>
       <xsd:enumeration value="LightBlue"/>
       <xsd:enumeration value="DarkBlue"/>
       <xsd:enumeration value="DarkGrey"/>
       <xsd:enumeration value="LightGrey"/>
       </xsd:restriction>
   </xsd:simpleType>

生成的代码是:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    public enum ColorCode {

         /// <remarks/>
         Red,

         /// <remarks/>
         Orange,

         /// <remarks/>
         LightGreen,

         /// <remarks/>
         DarkGreen,

         /// <remarks/>
         LightBlue,

         /// <remarks/>
         DarkBlue,

        /// <remarks/>
         DarkGrey,

         /// <remarks/>
         LightGrey,
     }

如何定义我的xsd,以便生成的代码如下所示:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
    [System.SerializableAttribute()]
    public enum ColorCode {

         /// <remarks/>
         Red = 0x12,

         /// <remarks/>
         Orange = 0x13,

         /// <remarks/>
         LightGreen = 0x17,

         /// <remarks/>
         DarkGreen=0x20,

         /// <remarks/>
         LightBlue=0x40,

         /// <remarks/>
         DarkBlue=0x50,

        /// <remarks/>
         DarkGrey0x90,

         /// <remarks/>
         LightGrey=0x190,
     }

1 个答案:

答案 0 :(得分:0)

前一段时间我遇到了同样的问题,但未找到答案。所以我最终得到了这样的解决方法:

private static readonly int[][] _conversion =
        {
            new[] {(int) ColorCode.Red, 0x12},
            new[] {(int) ColorCode.Orange, 0x13},
            new[] {(int) ColorCode.LightGreen, 0x17},
            .....
        };

    static int ToValue(ColorCode color)
    {
        if (_conversion.Any(c => c[0] == (int) color))
            return _conversion.First(c => c[0] == (int) color)[1];

        throw new NotImplementedException(string.Format("Color conversion is not in the dictionary! ({0})", color));
    }

    static ColorCode ToEnum(int value)
    {
        if (_conversion.Any(c => c[1] == value))
            return (ColorCode)_conversion.First(c => c[1] == value)[0];

        throw new NotImplementedException(string.Format("Value conversion is not in the dictionary! ({0})", value));
    }

    static void Main(string[] args)
    {
        Console.WriteLine(ToEnum(0x13));
        Console.WriteLine(ToValue(ColorCode.Red));
    }