cytinus
cytinus

Reputation: 5634

XML Schema Multiple Element Occurances

I am trying to develop an XML schema. It is for a survey, and example XML could look as follows.

<survey>
  <instructions>Please complete the survey.</instructions>
  <section>
    <sectionHeader>Multiple Choice: Select the most appropriate answer.</sectionHeader>
    <item>
      <question>What is your favorite color?</question>
      <answer>
        <option>red</option>
        <option>yellow</option>
        <option>blue</option>
      </answer>
    </item>
    <item>
      <question>What is your favorite shape?</question>
      <answer>
        <option>circle</option>
        <option>square</option>
        <option>triangle</option>
      </answer>
    </item>
  </section>
  <section>
    <sectionHeader>Free Response: Type a Response</sectionHeader>
    <item>
      <question>Who is your idol and why?</question>
      <answer>
        <textbox>Type your answer here.</textbox>
      </answer>
    </item>
  <section>
</survey>

Basically, an answer can either contain one or more options, or a single text box. Also the survey must contain one or more sections, each of which can contain one or more items. I currently have the following xml schema.

<xs:element name="survey">
  <xs:complexType>
    <xs:element name="instructions" type="xs:string"/>
    <xs:element name="section">
      <xs:complexType>
        <xs:element name="sectionHeader" type="xs:string"/>
        <xs:element name="item"/>
          <xs:complexType>
            <xs:element name="question" type="xs:string"/>
            <xs:element name="answer">
              ?? Choice between multiple options or one text box ??
            </xs:element>
          </xs:complexType>
        </xs:element>
      </xs:complexType>
    </xs:element>
  </xs:complexType>
</xs:element>

This however, only allows for one section and one item. I want to have it allow one or more of these tags in sequence. Also I want the answer tag to contain one or more options or a single textbox. How can I do this?

Upvotes: 0

Views: 391

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

Your groups of xs:element particles should be grouped inside xs:choice or xs:sequence, and you can specify minOccurs and maxOccurs either on the xs:element or the xs:choice / xs:sequence. So if you want the sequence (section, item, section, item, ...) use

<xs:sequence minOccurs="1" maxOccurs="unbounded">
  <xs:element name="section"/>
  <xs:element name="item"/>
</xs:sequence>

Upvotes: 1

Related Questions