是否有代码注释将 XML 属性限制为枚举值?
Are there code annotations to constrain XML attribute to an enum values?
在下面的 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>
在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".
下面是一个示例,说明如何为具有 XDocument
的 enum
的所有值生成 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())))))));
在下面的 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>
在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".
下面是一个示例,说明如何为具有 XDocument
的 enum
的所有值生成 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())))))));