代码之家  ›  专栏  ›  技术社区  ›  Revious

是否有将XML属性约束到枚举值的代码注释?

  •  0
  • Revious  · 技术社区  · 7 年前

    在下面的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>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Sebastian Hofmann Hassan Faghihi    7 年前

    在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”。

    下面是一个如何为 enum 具有 XDocument :

    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())))))));