简体   繁体   中英

XSD - XML element must contain exactly 1 of 2 possible sub elements

I am trying to build an XSD that will validate that R contains exactly 1 of either ITM or FCT. I have been unable to figure this out so far.

XML example:

<trs>
    <r NUM="1">
        <itm F01="123"/>
        <F65>1.00</F65>
    </r>
    <r NUM="2">
        <fct F02="345"/>
        <F65>2.00</F65>
    </r>
</trs>

XSD I have been playing around with:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="trs">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="r" maxOccurs="unbounded" minOccurs="1">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="itm" minOccurs="0">
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="xs:string">
                      <xs:attribute type="xs:short" name="F01"/>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
              <xs:element name="fct" minOccurs="0">
                <xs:complexType>
                  <xs:simpleContent>
                    <xs:extension base="xs:string">
                      <xs:attribute type="xs:short" name="F02"/>
                    </xs:extension>
                  </xs:simpleContent>
                </xs:complexType>
              </xs:element>
              <xs:element type="xs:float" name="F65"/>
            </xs:sequence>
            <xs:attribute type="xs:byte" name="NUM"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

This is easy, use a sequence of a choice (of the two elements) and the third element eg

 <xs:element name="r">
    <xs:complexType>
      <xs:sequence>
        <xs:choice>
          <xs:element ref="fct"/>
          <xs:element ref="itm"/>
        </xs:choice>
        <xs:element ref="F65"/>
      </xs:sequence>
      <xs:attribute name="NUM" use="required" type="xs:integer"/>
    </xs:complexType>
  </xs:element>

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