【问题标题】:Are there code annotations to constrain XML attribute to an enum values?是否有代码注释将 XML 属性限制为枚举值?
【发布时间】:2018-06-08 20:40:59
【问题描述】:

在以下 XML 代码中,IDFeature 和 IDView 属性的值必须与相应的枚举匹配。 c# 代码、DTD、XSD、Visual Studio 或 Resharper 是否允许指定此约束?

<MenuEntry Name="Menu_name_Reports"
               IDFeature="23"
               IDView="4" 
               Description=""
               ImagePath="/Resources/Menu/reports.png" />
</MenuEntry>

【问题讨论】:

    标签: c# xml xsd resharper dtd


    【解决方案1】:

    在 XSD 中,可以将属性限制为特定值;例如:

    <xs:attribute name="IDView">
        <xs:simpleType>
            <xs:restriction base="xs:string"> <!-- here you can set the base type -->
                <xs:enumeration value="value1"/> <!-- add all possible values here -->
                <xs:enumeration value="value2"/>
                <xs:enumeration value="value3"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    

    这里IDView的值只能是“value1”或“value2”或“value3”。

    下面是一个示例,说明如何为 enumXDocument 的所有值生成 XSD 的这一部分:

    enum Values { value1, value2, value3 };
    XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
    
    XDocument x = new XDocument(
        new XElement(xsd + "attribute",
            new XAttribute(XNamespace.Xmlns + "xs", "http://www.w3.org/2001/XMLSchema"),
            new XAttribute("name", "IDView"),
            new XElement(xsd + "simpleType",
                new XElement(xsd + "restriction",
                    new XAttribute("base", "xs:string"),
                    Enum.GetNames(typeof(Values)).Select(a => 
                        new XElement(xsd + "enumeration", 
                            new XAttribute("value", a.ToString())))))));
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 2011-12-19
      • 2019-03-08
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多