Search code examples
xmlxsdxsd-validationxml-validation

How to use XSD occurance indicators to denote at least one required


I'd like to create a element that requires at least 1 child to exist, but may have multiple occurrences of one or more child.

The following examples would all be valid :

<Parent>
    <ChildA></ChildA>
    <ChildB></ChildB>
</Parent>

<Parent>
    <ChildB></ChildB>
    <ChildA></ChildA>
</Parent>

<Parent>
    <ChildB></ChildB>
    <ChildA></ChildA>
    <ChildB></ChildB>
    <ChildB></ChildB>
    <ChildB></ChildB>
    <ChildA></ChildA>
</Parent>

This would be invalid:

<Parent>
</Parent>

I found this but it doesn't seem to allow a variable number of occurrences of any particular child.

all doesn't seem to allow for more than one occurrence either


Solution

  • This XSD,

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="Parent">
        <xs:complexType>
          <xs:choice maxOccurs="unbounded">
            <xs:element name="ChildA"/>
            <xs:element name="ChildB"/>
          </xs:choice>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    will successfully validate XML that has at least one of the listed child elements. Your valid examples will be considered valid, but not your invalid example.