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

Time:09-20

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>

CodePudding user response:

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

 <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>
  • Related