XSD Validation with If Else Possibility

user1884099 picture user1884099 · Dec 7, 2012 · Viewed 8.1k times · Source

Just trying to figure out if below scenario can be achieved through XSD schema level validation.


E.g-

<PreferredPlan>
This tag can have Values - Family or Single

if I got the value as "Family", I should be having below xml elements.

<Family>
<tag1></tag1>
<tag2></tag2>

If "Single" value is captured, I should have below tags.

<Single>
<tag3></tag3>
<tag4></tag4>
</Single>


Answer

C. M. Sperberg-McQueen picture C. M. Sperberg-McQueen · Dec 12, 2012

One simple way to define this would look something like this:

<xs:element name="PreferredPlan">
  <xs:complexType>
    <xs:choice>
      <xs:element ref="Family"/>
      <xs:element ref="Single"/>
    </xs:choice>
  </xs:complexType>
</xs:element>

<xs:element name="Family">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="tag1"/>
      <xs:element ref="tag2"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="Single">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="tag3"/>
      <xs:element ref="tag4"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="tag1" type="xs:string"/>  
<xs:element name="tag2" type="xs:string"/>  
<xs:element name="tag3" type="xs:string"/>  
<xs:element name="tag4" type="xs:string"/>

This allows

<PreferredPlan>
  <Family>
    <tag1/>
    <tag2/>
  </Family>
</PreferredPlan>

and

<PreferredPlan>
  <Single>
    <tag3/>
    <tag4/>
  </Single>
</PreferredPlan>

and forbids

<PreferredPlan>
  <Family>
    <tag3/>
    <tag4/>
  </Family>
</PreferredPlan>