简体   繁体   中英

XML schema unique constraint

I have an input XML schema like below and i wanted my schema to do 2 things as below as i am not sure on how to code the below 2 constraint.

  1. when an element "established" exists, the other element "planToEstablish" must not occured.Vice versa if the element "planToEstablish" exists, the "established" element must not exists.And both of the element may not exist as well.
  2. The Farm element needs to be validated by both of the "farmOwnerName" and the "produce" attribute. Example if farmOwnerName="Jerry" produce="apple", then we cannot allow another farm with the same farmOwnerName="Jerry" produce="apple" to be stored. But we can still store other farm element as long as the "produce" or the "farmOwnerName" is different.Example farmOwnerName="Jerry" produce="orange" can still be stored.

Below is the input XML file.

<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>

Below is the XML schema code that i have now.

<?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>

You first constraint is achived with a choice:

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

The second constraint is achieved with an xs:unique constraint on the Country element with selector set to "Farm", and fields @farmOwnerName and @produce.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM