XML模式唯一约束

时间:2012-11-24 05:32:22

标签: xml schema

我有一个像下面这样的输入XML模式,我希望我的模式可以执行以下两项操作,因为我不确定如何编写以下2条约束。

  1. 当存在元素“established”时,其他元素“planToEstablish”不得出现。反之,如果元素“planToEstablish”存在,则“既定”元素不能存在。并且这两个元素也可能不存在
  2. Farm元素需要通过“farmOwnerName”和“produce”属性进行验证。例如,如果farmOwnerName =“Jerry”productions =“apple”,那么我们就不能允许存储具有相同farmOwnerName =“Jerry”produce =“apple”的另一个服务器场。但是,只要“produce”或“farmOwnerName”不同,我们仍然可以存储其他farm元素。示例farmOwnerName =“Jerry”produce =“orange”仍然可以存储。
  3. 以下是输入XML文件。

    <Country>
     <farm farmOwnerName="Jerry" produce="apple">
       <established>1974</established>
       <totalWorker>30</totalWorker>
     </farm>
     <farm farmOwnerName="Ronald" produce="apple">
       <totalWorker>15</totalWorker>
     </farm>
     <farm farmOwnerName="Richard" produce="lemon">
       <planToEstablish>1970</planToEstablish>
       <totalWorker>20</totalWorker>
     </farm>
    </Country>
    

    下面是我现在拥有的XML架构代码。

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
    <xs:element name="established" type="xs:integer"/>
    <xs:element name="planToEstablish" type="xs:integer"/>
    <xs:element name="totalWorker" type="xs:integer"/>
    
    <xs:element name="Country">
    
    <xs:complexType name="farm">
    <xs:sequence maxOccurs="unbounded">
        <xs:element ref="established" use="optional"/>
        <xs:element ref="planToEstablish" use="optional"/>
        <xs:element ref="totalWorker"/>
    </xs:sequence>
    <xs:attribute name="farmOwnerName"  use="required"/>
    <xs:attribute name="produce"  use="required"/>
    <xs:attribute name="quality"  use="optional">
        <xs:simpleType>
            <xs:restriction base="xs:token">
                <xs:enumeration value="best"/>
                <xs:enumeration value="normal"/>
                <xs:enumeration value="low"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    

1 个答案:

答案 0 :(得分:0)

您可以选择第一个约束:

<xs:choice minOccurs="0">
    <xs:element ref="established" use="optional"/>
    <xs:element ref="planToEstablish" use="optional"/>
</xs:choice>

第二个约束是通过对Country元素使用xs:unique约束来实现的,其中选择器设置为“Farm”,字段为@farmOwnerName和@produce。

相关问题