Categories
programming

XSD minOccurs Specified And The XmlSerializer

In your XSD schema definitions, the minOccurs has a subtle nuance through a leaky abstraction. Getting right to the point:

Let’s take an element definition such as:

<xs:element name="OptString" type="xs:string" minOccurs="0"/>

Now when you create your default classes using the xsd.exe tool, you will end up with a class having a property OptString. Neat, since in code, you can just set that property (or not) and it will appear in the XML (or not). It’s optional.

Now what about:

<xs:element name="OptBool" type="xs:boolean" minOccurs="0"/>

Again, there will be a property named OptBool for you to set (or not). Only this time, it won’t appear in the serialized XML. There’s an additional property named OptBoolSpecified which you need to set. If false (which it is by default) then it won’t serialize.

Now, let’s look at:

<xs:element name="OptValueString" type="ValueString" minOccurs="1"/>

where ValueString is defined as:

<xs:simpleType name="ValueString">
    <xs:restriction base="xs:string">
      <xs:minLength value="3" />
      <xs:maxLength value="10" />
    </xs:restriction>
  </xs:simpleType>

This has the same effect as a regular string. If it’s set (or not), it will serialize (or not).

Then we have a custom type (an enumeration) such as:

<xs:element name="OptStrongString" type="TypedString" minOccurs="0"/>

where TypedString is defined as:

<xs:simpleType name="TypedString">
    <xs:restriction base="xs:string">
      <xs:enumeration id="ValueA" value="A" />
      <xs:enumeration id="ValueB" value="B" />
    </xs:restriction>
  </xs:simpleType>

It has it’s base in type String, but it’s an enumeration, so how will it behave?

Well, it needs it’s related Specified property to be set. Without that, it’s not going to serialize. And the same goes for type int.

In fact, experiment with the different types and understand the subtleties of minOccurs better. And you could question the existential “why” it is so or you could also just accept the way it is and move swiftly along 🙂

I’ve attached some code here to jumpstart your experimentation.

Download project XSDMinOccursSandbox