Search code examples
xmlxsdxml-validation

XML validation with XSD: how to avoid caring about the sequence of the elements?


I have following XSD code:

<xsd:complexType name="questions">
    <xsd:sequence>
        <xsd:element name="location" type="location"/>
        <xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
        <xsd:element name="pictureInput" type="pictureInput" minOccurs="0"/>
    </xsd:sequence>
</xsd:complexType>

The problem here is: the elements location, multipleChoiceInput, etc. must appear in the same order they are declared. I don't want this to happen, I want that, in the validation process the sequence should not be relevant. How can I achieve this?

Another possibility I've tried has been:

<xsd:complexType name="questions">

        <xsd:choice maxOccurs="unbounded">   
            <xsd:element name="location" type="location"/>  
            <xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
            <xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
            <xsd:element name="pictureInput" type="pictureInput" minOccurs="0" maxOccurs="1"/>
        </xsd:choice>            

</xsd:complexType>

In this example, the sequence really does not matter anymore, and I can have so much elements as I want (what "all" would not allow me to do). But I still have the Problem with the min- and maxOccurs. In this example, I could have so many "pictureInput"s as possible, what is againt the constraint that I would like to have either 0 or 1.

Thanks a lot for helping!


Solution

  • <xsd:complexType name="questions">
        <xsd:all>
            <xsd:element name="location" type="location"/>
            <xsd:element name="multipleChoiceInput" type="multipleChoiceInput"/>
            <xsd:element name="textInput" type="textInput"/>
            <xsd:element name="pictureInput" type="pictureInput"/>
        </xsd:all>
    </xsd:complexType>
    

    NOTE: I have changed "sequence" to "all"

    Sequence forces order (as defined). if order doesn't matter then all is used.

    If there are chances of element occurence more than once then xsd:any can be used.

    <xsd:complexType name="questions">
        <xsd:sequence>
            <xsd:any minOccurs="0"/>
        </xsd:sequence>
    </xsd:complexType>
    

    You can find details of xsd:any at following link:

    https://www.w3schools.com/xml/schema_complex_any.asp