Home > Enterprise >  XSD describing arbitrary number of same child elements - xs:all / xs:sequence / xs:choice and cardin
XSD describing arbitrary number of same child elements - xs:all / xs:sequence / xs:choice and cardin

Time:06-08

I am trying to describe something like the following XML in XSD:

<componentDefinitions>
   <component id ="1"/>
   <component id ="2"/>
</componentDefinitions>

There are some additional constraints:

  • there is only one componentDefinition block
  • the componentDefiniton block can be empty or it contains an arbitrary number of component elements
  • component elements may occur in any order

My solution to this is the following XSD:

<xs:element name="componentDefinitions">
   <xs:complexType>
      <xs:choice minOccurs="0">
         <xs:element name="component" minOccurs="0" maxOccurs="unbounded">
            <xs:complexType>
               <xs:attribute name="id" type="xs:string" use="required" />
            </xs:complexType>
         </xs:element>
      </xs:choice>
   </xs:complexType>
</xs:element>

However, this feels not correct since I am using xs:choice and at the same time I declare that it is ok to "choose" all contents of xs:choice.

Using xs:all instead seemed to be the correct solution for me but it is not allowed to set maxOccurs="unbounded".

xs:sequence doesn't seem to be correct either since the component elements may occur in any order.

So here is my question: Is there any other (more simple) solution to this?

CodePudding user response:

You're right that there are multiple ways of specifying multiple child elements.

In your case, since only elements with the same name are possible children, the notion of unordered is superfluous. (BTW, in practice, unordered is commonly more trouble than it's worth anyway.) What's commonly done in situations like this is to use xs:sequence around child xs:element with maxOccurs="unbounded".

See also

  • Related