XML Schema如何限制元素的数量

时间:2013-11-06 15:32:21

标签: xml xsd xml-validation

如何使每条记录具有相同的值?现在每个记录可以有不同的值。

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
 <element name="list">
  <complexType>
   <sequence>
    <element name="record" minOccurs="0" maxOccurs="unbounded">
     <complexType>
      <sequence>
       <element name="value" type="string" minOccurs="0" maxOccurs="unbounded"/>
      </sequence>
     </complexType>
    </element>
   </sequence>
  </complexType>
 </element>
</schema>

对于此架构,此xml将有效:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <record>
        <value>value 11</value>
        <value>value 12</value>
        <value>value 13</value>             
    </record>
    <record>
        <value>value 21</value>
        <value>value 22</value>
        <value>value 23</value>             
    </record>
</list>

这也是有效的:

<?xml version="1.0" encoding="UTF-8"?>
    <list>
        <record>
            <value>value 11</value>
            <value>value 12</value>
            <value>value 13</value>             
        </record>
        <record>
            <value>value 21</value>
            <value>value 22</value>
            <value>value 23</value>
            <value>value 24</value>
            <value>value 25</value>
        </record>
    </list>

如何更改架构以使第二个xml文件无效?

1 个答案:

答案 0 :(得分:0)

似乎XSD 1.0唯一可行的解​​决方案是定义多个记录元素:

<xs:element name="list">
  <xs:complexType>
    <xs:choice>
      <xs:element name="record1" minOccurs="0" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element ref="value" minOccurs="1" maxOccurs="1" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="record2" minOccurs="0" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element ref="value" minOccurs="2" maxOccurs="2" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="record3" minOccurs="0" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element ref="value" minOccurs="3" maxOccurs="3" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <!-- and so on... -->
    </xs:choice>
  </xs:complexType>
</xs:element>

<xs:element name="value" type="xs:string" />

但XML会有所不同:

<list>
  <record3>
    <value>value 11</value>
    <value>value 12</value>
    <value>value 13</value>
  </record3>
  <record3>
    <value>value 21</value>
    <value>value 22</value>
    <value>value 23</value>
  </record3>
</list>