控制元素基数是否基于XSD中的属性枚举?

时间:2016-05-10 01:16:29

标签: xml xsd xsd-validation xml-validation

如果character @type为cellfillednumberedspecialNumbered,我希望specialUnnumbered元素可重复。如果character @type为cellmultiCharacterNumbered,我希望multiCharacterUnnumbered元素不可重复。

如果cell类型为blank,我想完全禁止使用character元素。

这需要XSD 1.1吗?我如何形成条件或测试?

<xs:element name="cell" maxOccurs="unbounded">
    <xs:complexType>
         <xs:sequence>
             <xs:element name="character" type="xs:string" minOccurs="0"/>
         </xs:sequence>
         <xs:attribute name="type" use="required">
              <xs:simpleType>
                   <xs:restriction base="xs:string">
                        <xs:enumeration value="filled"/>
                        <xs:enumeration value="blank"/>
                        <xs:enumeration value="numbered"/>
                        <xs:enumeration value="specialNumbered"/>
                        <xs:enumeration value="specialUnnumbered"/>
                        <xs:enumeration value="multiCharacterNumbered"/>
                        <xs:enumeration value="multiCharacterUnnumbered"/>
                   </xs:restriction>
               </xs:simpleType>
          </xs:attribute>
      </xs:complexType>
  </xs:element>

1 个答案:

答案 0 :(得分:1)

是的, XSD 1.1 (不是XSD 1.0)可以表达您的复杂约束:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">
  <xs:element name="cell">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="character" type="xs:string" 
                    minOccurs="0"  maxOccurs="unbounded"/>
      </xs:sequence>
      <xs:attribute name="type" use="required">
        <xs:simpleType>
          <xs:restriction base="xs:string">
            <xs:enumeration value="filled"/>
            <xs:enumeration value="blank"/>
            <xs:enumeration value="numbered"/>
            <xs:enumeration value="specialNumbered"/>
            <xs:enumeration value="specialUnnumbered"/>
            <xs:enumeration value="multiCharacterNumbered"/>
            <xs:enumeration value="multiCharacterUnnumbered"/>
          </xs:restriction>
        </xs:simpleType>
      </xs:attribute>
      <xs:assert test="(   (@type = 'blank' and count(character) = 0)
                        or (@type = ('multiCharacterNumbered', 'numbered',
                                     'specialNumbered', 'specialUnnumbered') 
                            and count(character) = (0,1))
                        or (@type = ('filled', 'multiCharacterUnnumbered')))"/>
    </xs:complexType>
  </xs:element>
</xs:schema>