The behaviour you observe is normal: *Specified
fields are generated only when using the XmlSerializer.
The DataContractSerializer never generates those Specified field. Instead. it will set the IsRequired
property of the DataMember
attribute to false (this is the default value of this property, so you won't even see it in the attribute).
Outgoing messages
You want to omit fields which have no value in outgoing messages.
The problem is that DateTime
is a value type, which means that even if it is not set, it has a default value of "0001-01-01T00:00:00".
If you don't want to output it in the outgoing message, you can:
- Add the
EmitDefaultValue = false
property to theDataMember
attribute. This will prevent the element from being written at all in the generated xml. - Alternatively, change the type to
DateTime?
=> this will output something like<dateMaxValueField i:nil="true"/>
in your xml document.
Without modifying the proxy, there is no way to do it.
Incoming messages
The same logic applies: you will have no problem receiving messages which omit an element completely (as long as the corresponding property in the proxy class has IsRequired = false
). Please note that as DateTime
is a value type, you will always have it populated with its default value ("0001-01-01"). If you prefer to receive a null
instance, then you need to modify your proxy and use the DateTime?
type.
However, if you want to be able to parse a message containing:
<dateMaxValueField></dateMaxValueField>
then I'm afraid there is no way to do it with the DataContractSerializer.
note: The XmlSerializer allows for greater flexibility in those scenarios (when precise control over the XML is required, for compatibility reasons for instance).