Search code examples
xmlxsdschemakeyref

How to Implement Conditional Schema Validation


How Can i implement a schema validation that can serve the following requirement

<test>
  <e1>abc</e1>
  <e2>
     <e21>xxx</e21>
     <e22>yyy</e22>
  </e2>
</test>

so my requirement is that e22 cannot be null if e21 is not null, so how can i design my xsd schema


Solution

  • The requirement "e22 cannot be null if e21 is not null" means, I think, that either e21 and e22 are both null, or neither is.

    If a null value for e21 and e22 is conveyed by having the elements be absent, a simple content model does the trick:

    <complexType name="e2">
      <sequence minOccurs="0" maxOccurs="1">
        <element ref="e21"/>
        <element ref="e22"/>
      </sequence>
    </complexType>
    

    Here either both e21 and e22 are present in the document, or neither is.

    If you also want to allow the case that e21 is absent (null) and e22 is not, then change the sequence to

      <sequence minOccurs="0" maxOccurs="1">
        <element ref="e21" minOccurs="0"/>
        <element ref="e22"/>
      </sequence>
    

    If by "being null" you mean "being empty", then there is no way to enforce the constraint in XSD 1.0; in XSD 1.1 you can use assertions to express and enforce relatively complex constraints. Look for Stack Overflow questions about co-constraints and assertions in XSD 1.1.