问题
I want to add a name-attribute to all my elements. To make sure that only some attribute values are allowed I created a restriction-pattern. Is there a way to make sure, that each enumeration value is used exactly once per document?
simpleStyle:
<xsd:simpleType name="myname">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="1"/>
<xsd:enumeration value="2"/>
</xsd:restriction>
</xsd:simpleType>
XML
<element name="1"/>
<element name="2"/>
<element name="1"/>
The last one should not be allowed.
Is that even possible?
回答1:
There is a similar concept called identity constraints, which may suit your purposes. You want to use xs:unique
, which is a constraint on the parent element, not a property of an enumeration. Something like:
<xs:unique name="myconstraint">
<xs:selector xpath=".//*"/>
<xs:field xpath="@name"/>
</xs:unique>
The selector
says which child elements the constraint applies to (all descendants in this example), and the field
indicates which part must be unique.
回答2:
As correctly suggested by @xan and by this guide, you could change your code this way:
Define the
myname
enumeration.
This will allow only the usage of1
or2
values.<!-- The Enumeration definition (allowing only values 1 or 2) --> <xsd:simpleType name="myname"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="1"/> <xsd:enumeration value="2"/> </xsd:restriction> </xsd:simpleType>
Define the
element
structure.
This will define the structure for the<element name="..." />
node.<!-- the element definition (defines the <element /> structure) --> <xs:complexType name="elementType"> <xs:attribute name="name" type="myname" use="required"/> </xs:complexType>
Univque usage.
Define theelement
tag usage requiring an univoque usage of thename
attribute.<xs:element name="myelements"> <!-- The <element/> tag usage --> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="element" type="myname"/> </xs:sequence> </xs:complexType> <!-- The univocity constraint --> <xs:unique name="nameUniqueConstraint"> <xs:selector xpath="element"/> <xs:field xpath="@name"/> </xs:unique> </xs:element>
Please note that nameUniqueConstraint
is just an arbitrary name to identify the constraint you want.
来源:https://stackoverflow.com/questions/5687500/xml-schema-how-to-set-enumerations-to-one-appearance-per-document