Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

XML schema for no sequence and multiple occurs

  1. I need to create a schema for validate a XML file.
  2. The elements inside Mother tag can be Son or Daughter
  3. Son or Daughter element do not have any sequence.
  4. Son cannot me multiple element (Only one son).
  5. But Daughter can be multiple (Multiple daughters).

So my question is how to write a XML schema for this. This is what I wrote. Instead of <xsd:all> I tried <xsd:sequence> and <xsd:choice> also. But I couldn't figure out how to overcome this.

<xsd:complexType name="Mother">     
 <xsd:all>
  <xsd:element name="Son" type="string" minOccurs="0" maxOccurs="1"/>
  <xsd:element name="Daughter" type="string" minOccurs="0" maxOccurs="1"/>
 </xsd:all>
</xsd:complexType>

-------------------------------These are the correct XML files--------------------------------

With Multiple daughters

<Mother>
<Son>Jhon</Son>
<Daughter>Rose</Daughter>
<Daughter>Ann</Daughter>
</Mother>

With different sequence

<Mother>
<Daughter>Rose</Daughter>
<Son>Jhon</Son>
<Daughter>Ann</Daughter>
</Mother>

Without Son or Without Daughter or Without both

<Mother>
<Daughter>Rose</Daughter>
</Mother>

Upvotes: 2

Views: 1039

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

In this particular case you could do it as a sequence of zero or more Daughter elements, followed by zero or one Son and then another zero or more Daughters

<xsd:complexType name="Mother">     
 <xsd:sequence>
  <xsd:element name="Daughter" type="string" minOccurs="0" maxOccurs="unbounded"/>
  <xsd:element name="Son" type="string" minOccurs="0" maxOccurs="1"/>
  <xsd:element name="Daughter" type="string" minOccurs="0" maxOccurs="unbounded"/>
 </xsd:sequence>
</xsd:complexType>

If the element content were more complex than just a string I'd be inclined to declare separate top level elements and reference them using <xsd:element ref="Daughter" minOccurs=....

Upvotes: 2

Related Questions