美文网首页
简单定义schema约束(XML入门13)

简单定义schema约束(XML入门13)

作者: 北荒客 | 来源:发表于2020-03-04 02:48 被阅读0次

         学习写schema文档约束(facets)内容特别多,好在很简单,使用时查资料就可以解决。但是,有个前提,你必须懂得什么是约束。约束就是限制。例如:年龄,一个人的年龄不可能成千上万,所以,做幼儿园登记时,年龄写30岁肯定不合逻辑。这就是是对元素标记的限定。再不如设定秘码必须八位,就必须在数据中进行约束。

          我们还是使用官网例子。

           对数值的限定例子:

    <xs:element name="age">

     <xs:simpleType>

    <xs:restricton  base="xs:integer"/>

    <xs:minInclusive value="0"/>

    <xs:maxInclusive value="120"/>

    </xs:restriction>

    </xs:simpleType>

    </xs:element>

            我们在写约束时,照胡楼画瓢就可以。限制(restriction),最小值(mininclusive),最大值(maxinclusive),基础(base),数值(value)。

         其实这就是定义一个简单元素标记: <age></age>。在使用是,标记之间所填的数据要在0和120之间才有效。否则不合法。

         如果不做限定,指定义一个简单元素就用第一句话,加个类型即可。例如:

    <xs:element  name="age" type=“xs:integer”/>

           对数值限定在一组值,其他的都不接受。使用枚举(enumeration)指令。

         例如:

    <xs:element name="car">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:enumeration value="Audi"/>

    <xs:enumeration value="Golf"/>

      <xs:enumeration value="BMW"/>

    </xs:restriction></xs:simpleType>

    </xs:element>

           这个例子,把小汽车的品牌固定在三个品牌,不允许使用其他品牌。

           在schema文档使用最多的是模式约束(pattern constraint),是一种严格约束模式。举个对性别约束的下列子:

    <xs:element  name="gender">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:pattern value="male|female"/>

    </xs:restriction></xs:simpleType>

    </xs:element>

         这个约束,对简单元素标记: <gender></gender>之间只能是非男即女。

         用模式约束(pattern constraint)限定小写字母,例如:

    <xs:element name="letter">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:pattern value="[a-z]"/>

    </xs:restriction>

    </xs:simpleType>

    </xs:element>

        这个例子,对元素标记<letter></letter>之间只能填写26个小写字母。如果letter标记之间写三个大写字母,可以如下定义,例如:

    <xs:element name="letter">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:pattern value="[A-Z] [A-Z][A-Z]"/>

    </xs:restriction>

    </xs:simpleType>

    </xs:element>

          如果,对元素标记<letter></letter>之间限定填写三个任意大小写字母,可以如下定义。例如:

    <xs:element name="letter">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:pattern value="[a-zA-Z][a-zA-Z] [a-zA-Z]"/>

         </xs:restriction>

    </xs:simpleType>

    </xs:element>

        如果,对元素标记<letter></letter>之间限定填写一个任意大小写字母或数字,可以如下定义。例如:

    <xs:element name="letter">

     <xs:simpleType>

    <xs:restricton  base="xs:string"/>

    <xs:pattern value="[a-zA-Z0-9]"/>

         </xs:restriction>

    </xs:simpleType>

    </xs:element>

          虽然使用模式约束(pattern constraint)比较啰嗦,但是,写多了就简单了。非常自然,使用限定的方式与你想象的差不多。

           以上是简单约束,还有一些比较复杂的约束。容后再续。

              北荒客

               2020.3.4

    相关文章

      网友评论

          本文标题:简单定义schema约束(XML入门13)

          本文链接:https://www.haomeiwen.com/subject/ewtelhtx.html