I have an xsd schema with an optional element (minOccurs=0
, maxOccurs=1
) of type int
. The element is NOT defined as nillable. In the data model I would like to map this to a field of .net type Nullable<int>
, where a null
value should correspond to the element being omitted in the xml.
However, using the XmlSerializer
, it seems I have to declare a nullable field in the datamodel with [XmlElement IsNullable=true]
. If I set IsNullable=false
, I get the exception "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." But if I understand correctly, setting IsNullable=true
(or leaving the attribute out) is implicitly setting the element to nillable, and thereby changing the schema.
This is schema-first design, so I can't just add 'nillable' to the elements in the schema.
How do I map nullable .net types to non-nillable xml elements?
(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.)
Edit: Thanks to the comments I now understand the problem better. There is really two separate issues:
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?
XmlSerializer requires nullable types in the data model to have
[XmlElement IsNullable=true]
, which means the model implicitly adds 'nillable' to the schema. Can I avoid this?