XML-Schema: how to set enumerations to one appearance per document

南笙酒味 提交于 2019-12-24 10:36:27

问题


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:

  1. Define the myname enumeration.
    This will allow only the usage of 1 or 2 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>
    
  2. 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>
    
  3. Univque usage.
    Define the element tag usage requiring an univoque usage of the name 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!