title: Serialize nullable type to optional non-nillable element
body: <p>I have an xsd schema with an optional element (<code>minOccurs=0</code>, <code>maxOccurs=1</code>) of type <code>int</code>. The element is NOT defined as nillable. In the data model I would like to map this to a field of .net type <code>Nullable&lt;int&gt;</code>, where a <code>null</code> value should correspond to the element being omitted in the xml.</p>
  
  <p>However, using the <code>XmlSerializer</code>, it seems I <em>have</em> to declare a nullable field in the datamodel with <code>[XmlElement IsNullable=true]</code>. If I set <code>IsNullable=false</code>, I get the exception "<em>IsNullable may not be set to 'false' for a Nullable type."IsNullable may not be set to 'false' for a Nullable type. Consider using 'System.Int32' type or removing the IsNullable property from the XmlElement attribute.</em>" But if I understand correctly, setting <code>IsNullable=true</code> (or leaving the attribute out) is implicitly setting the element to nillable, and thereby changing the schema.</p>
  
  <p>This is schema-first design, so I can't just add 'nillable' to the elements in the schema.</p>
  
  <p>How do I map nullable .net types to non-nillable xml elements?</p>
  
  <p>(I understand that I can omit nil-elements when serializing to xml by using XxxSpecified properties in the data model, but this approach still requires adding nillable to the xsd schema, as far as I can tell.)</p>
  
  <p><strong>Edit</strong>: Thanks to the comments I now understand the problem better. There is really two separate issues:</p>
  
  <ol>
  <li><p>Schema-to-code generators like xsd.exe creates a non-nullable
  type in the generated model if the schema element is non-nillable
  (even if it is optional). Can I override this (using any known code
  generator) so I get nullable types in the generated code?</p></li>
  <li><p>XmlSerializer requires nullable types in the data model to have
  <code>[XmlElement IsNullable=true]</code>, which means the model implicitly adds
  'nillable' to the schema. Can I avoid this?</p></li>
  </ol>