RSS

Tag Archives: xsd

xsd quiz

I recently needed to solve an XSD problem. I needed to define a schema that allows this:

<Element>
  <FIRSTValue>abcde</FIRSTValue>
  <SECONDValue>12345</SECONDValue>
</Element>

where FIRSTValue is not mandatory, SECONDValue is not mandatory but either one of them or both must exists.

I started using a “sequence”

<xs:complexType name="AltType">
    <xs:sequence>
      <xs:element type="xs:string" name="FIRSTValue" minOccurs="0" />
      <xs:element type="xs:string" name="SECONDValue" minOccurs="0" />
    </xs:sequence>
</xs:complexType>

but this allows 0 children…

I then tried an “all”:

<xs:complexType name="AltType">
    <xs:all>
      <xs:element type="xs:string" name="FIRSTValue" minOccurs="0" />
      <xs:element type="xs:string" name="SECONDValue" minOccurs="0" />
    </xs:all>
</xs:complexType>

and this also allows 0 children…

Ok let’s think about a “choice”:

<xs:complexType name="AltType">
    <xs:choice>
      <xs:element type="xs:string" name="FIRSTValue" minOccurs="0" />
      <xs:element type="xs:string" name="SECONDValue" minOccurs="0" />
    </xs:choice>
</xs:complexType>

Ouch! I can’t have BOTH children …

Ok, the choice is surely the way:

<xs:complexType name="AltType">
    <xs:choice>
      <xs:element type="xs:string" name="FIRSTValue"  />
      <xs:element type="xs:string" name="SECONDValue"   />
      <xs:sequence>
        <xs:element type="xs:string" name="FIRSTValue" />
        <xs:element type="xs:string" name="SECONDValue" />
      </xs:sequence>
    </xs:choice>
</xs:complexType>

but this is evalued as a “non deterministic” choice and doesn’t compile.

Finally the solution (because yes, it IS possible). Note: to avoid an empty node I defined a new type of string with minimum length = 1.

  <xs:simpleType name="notEmptyString">
    <xs:restriction base="xs:string">
      <xs:minLength value="1" />
    </xs:restriction>
  </xs:simpleType>

  <xs:complexType name="AltType">
    <xs:choice>
      <xs:sequence>
        <xs:element type="notEmptyString" name="FIRSTValue" />
        <xs:element type="xs:string" name="SECONDValue" minOccurs="0" />
      </xs:sequence>
      <xs:element type="notEmptyString" name="SECONDValue" />
    </xs:choice>
  </xs:complexType>
Advertisements
 
Leave a comment

Posted by on 2016/06/30 in dev

 

Tags: , ,