Search code examples
xmlxsdxsd-validationxml-validation

Is there a way to nest complexTypes without a wrapper tag?


I have a <choice> that I need to pull out of its current element into its own type (so that it can be referenced by other complexTypes). Is there a way to do that without needing a wrapper tag?

This is what I have so far:

The complex type:

<xs:complexType name="MyType">
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element ref="type1"/>
            <xs:element ref="type2"/>
        </xs:choice>
</xs:complexType>  

And referencing it

<xs:complexType name="AdaptabilitySettingMetadataBase" abstract="true">
    <xs:sequence>
        <!-- other elements -->
        <xs:element name="MyTypeInClass" type="MyType"
                    minOccurs="0"  maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

This works, but only allows me to put the type1 and type2s within the tag MyTypeInClass, which I don't want. Any ideas?


Solution

  • Use xs:group rather than xs:complexType to achieve your goal:

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
               xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns="http://www.esocial.gov.br/schema/evt/evtCS/v02_02_00"
               targetNamespace="http://www.esocial.gov.br/schema/evt/evtCS/v02_02_00"
               elementFormDefault="qualified" attributeFormDefault="unqualified">
    
      <xs:element name="elem1"/>
      <xs:element name="elem2"/>
    
      <xs:group name="MyType">
        <xs:choice>
          <xs:element ref="elem1"/>
          <xs:element ref="elem2"/>
        </xs:choice>
      </xs:group>
    
      <xs:complexType name="AdaptabilitySettingMetadataBase" abstract="true">
        <xs:sequence>
          <!-- other elements -->
          <xs:group ref="MyType" minOccurs="0"  maxOccurs="unbounded"/>
        </xs:sequence>
      </xs:complexType>     
    </xs:schema>