Optional Elements

Elements within a sequence definition may be declared to be optional by using the minOccurs="0" facet. This indicates that the element is not required in the encoded message. An additional construct is added to the generated code to indicate whether an optional element is present in the message or not. This construct is a bit structure placed at the beginning of the generated sequence structure or class. This structure always has variable name m (for ‘mask’) and contains single-bit elements of the form ‘elemNamePresent’ as follows:

   struct {
      unsigned elemName1Present : 1,
      unsigned elemName2Present : 1,
      ...
   } m;

In this case, the elements included in this construct correspond to only those elements marked as optional (i.e. with minOccurs="0" facet) within the sequence group definition. If a sequence contains no optional elements, the entire construct is omitted.

For example, the following XSD sequence definition declares one optional and one required element:

   <xsd:complexType name="SeqWithOptElem">
      <xsd:sequence>
         <xsd:element name="reqElem" type="xsd:string"/>
         <xsd:element name="optElem" type="xsd:integer" minOccurs="0"/>
      </xsd:sequence>
   </xsd:complexType>

The C type that is generated for this XSD type is as follows:

   typedef struct SeqWithOptElem {
      struct {
         unsigned optElemPresent : 1;
      } m;
      const OSXMLSTRING reqElem;
      OSINT32 optElem;
   } SeqWithOptElem;

In this case, if the optElemPresent flag is set to FALSE in a variable of this type, the contents of the optElem field will not be included in an encoded XML instance of the type. Similarly, after decoding, the optElemPreseent flag can be tested to see if the message that was decoded contained this element. If this value is FALSE, the contents of the optElem field in the variable are undefined.

The C++ case is similar except that the mask structure is contained within the generated C++ class definition:

   class SeqWithOptElem : public OSRTBaseType {
   public:
      struct {
         unsigned optElemPresent : 1;
      } m;
      const OSXMLStringClass reqElem;
      OSINT32 optElem;
      ...
   } ;

The constructors for this class (not shown) will set all bits in the mask to zero.