【问题标题】:XML schema unique constraintXML 模式唯一约束
【发布时间】:2012-11-24 17:19:36
【问题描述】:

我有一个如下所示的输入 XML 架构,我希望我的架构执行以下 2 件事,因为我不确定如何编写以下 2 个约束。

  1. 当一个元素“建立”存在时,另一个元素“planToEstablish”不能出现。反之,如果元素“planToEstablish”存在,“建立”元素一定不存在。并且这两个元素也可能不存在.
  2. Farm 元素需要同时通过“farmOwnerName”和“produce”属性进行验证。例如,如果farmOwnerName="Jerry"produce="apple",那么我们不能允许存储具有相同farmOwnerName="Jerry"produce="apple" 的另一个农场。但是我们仍然可以存储其他农场元素,只要“produce”或“farmOwnerName”不同。示例farmOwnerName="Jerry"produce="orange"仍然可以存储。

下面是输入的 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>

【问题讨论】:

    标签: xml schema


    【解决方案1】:

    你的第一个约束是通过一个选择来实现的:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多