Search code examples
xmlxsdxsd-validationxml-validation

XSD for one element out of a group of elements preceding another?


The child elements of a parent element must have one element (out of a group) followed by another specific element.

<xsd:element name="elementContainer">
    <xsd:element name="element1">
    <xsd:element name="element2">
    <xsd:element name="element3">
    <xsd:element name="element4">
    <xsd:element name="element5">
    <xsd:element name="element6">
    <xsd:element name="proceedingElement">
</xsd:element>

I want to modify the XSD above so that there must be one element(1-6) followed by the proceeding element.

I've tried wrapping a choice around the elements 1 to 6 but that is not being picked up by validation.

<xsd:element name="elementContainer">
    <xsd:choice minOccurs="1">
        <xsd:element name="element1">
        <xsd:element name="element2">
        <xsd:element name="element3">
        <xsd:element name="element4">
        <xsd:element name="element5">
        <xsd:element name="element6">
    </xsd:choice>
    <xsd:element name="proceedingElement">
</xsd:element>

For the two following examples I would like the first to pass validation and the second to fail.

<elementContainer>
    <element2/>
    <proceedingElement/>
</elementContainer>

<elementContainer>
    <proceedingElement/>
</elementContainer>

The fact that there is a proceeding element could even be ignored if that helps, so just making sure that at least one element out of the six elements exists would work.


Solution

  • You have the right basic idea regarding xsd:choice, but there are numerous problems with your XSD:

    • xsd:element elements are not closed.
    • xsd:complexType and xsd:sequence are missing.

    With corrections for the above issues, and dropping default xsd:choice/@minOccurs = 1, this XSD,

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" > 
      <xsd:element name="elementContainer">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:choice>
              <xsd:element name="element1"/>
              <xsd:element name="element2"/>
              <xsd:element name="element3"/>
              <xsd:element name="element4"/>
              <xsd:element name="element5"/>
              <xsd:element name="element6"/>
            </xsd:choice>
            <xsd:element name="proceedingElement"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    

    will require that there be one of element1 through element6 followed by one proceedingElement, as requested.