Daniel Green
Daniel Green

Reputation: 644

What is the proper way in xsd to define a set of elements that may be child elements and may repeat?

I am trying to determine the proper way using an xsd schema to define an element that may contain any of a set of child elements including possible repeat child elements.

For example, given the following XML document:

<?xml version="1.0" encoding="utf-8" ?>
<EncounterDefinitions
  xmlns="http://lavendersoftware.org/schemas/SteamGame/Data/Xml/Encounters.xsd">
  <Encounter name="Sample Encounter">
    <Task>
      <Weapon/>
      <Weapon/>
      <Information/>
    </Task>
    <Task>
      <Tool count="3"/>
      <Ritual/>
    </Task>
  </Encounter>
</EncounterDefinitions>

I've managed to sus out the XSD this far.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Encounters"
    targetNamespace="http://lavendersoftware.org/schemas/SteamGame/Data/Xml/Encounters.xsd"
    elementFormDefault="qualified"
    xmlns="http://lavendersoftware.org/schemas/SteamGame/Data/Xml/Encounters.xsd"
    xmlns:mstns="http://lavendersoftware.org/schemas/SteamGame/Data/Xml/Encounters.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>    
  <!-- attribute types -->
  <xs:attribute name="name"  type="xs:string" />

  <!-- complex types -->

  <xs:element name="Task">
    <xs:complexType>
      <xs:sequence>
        <!-- This type here should be any of a set of Elements -->
        <xs:element name="Objective" type="Objective"/>
      </xs:sequence>
    </xs:complexType>  
  </xs:element>

  <xs:element name="Encounter">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="Task"/>
      </xs:sequence>
      <xs:attribute ref="name" use="required"/>
    </xs:complexType>
  </xs:element>

  <xs:element name="EncounterDefinitions">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="Encounter"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Upvotes: 0

Views: 792

Answers (1)

Michael Kay
Michael Kay

Reputation: 163587

If there are no constraints on the order of the children or the number of occurrences of each, use a repeating choice:

<xs:complexType>
  <xs:choice maxOccurs="unbounded">
    <xs:element name="Objective" type="Objective"/>
    <xs:element name="Weapon" type="Weapon"/>
    <xs:element name="Information" type="Information"/>
  </xs:sequence>
</xs:complexType>

Upvotes: 1

Related Questions