Reputation: 191
I am generating a client proxy from a webservice using svcutil. The WSDL contains elements that have the attribute minOccurs set to 0
<xsd:element minOccurs="0" name="dateMaxValue" type="xsd:dateTime"></xsd:element>
However the generated DataContract completly ignores this attribute and just create a normal dateMaxValue attribute without any dateMaxValueSpecified attribute
private System.DateTime dateMaxValueField;
When I generate the proxy using option /serializer:XmlSerializer, I get the xxxSpecified properties.
private System.DateTime dateMaxValueField;
private bool dateMaxValueFieldSpecified;
EDIT
For optional field, I want the field not being sent or not being read when they have no values (equivalent of specified=false with XmlSerializer) Currently incoming and outcoming data are set to default values. How can I obtain a similar behaviour with the DataContractSerializer ? Or if it is already there, how can I use it ?
Upvotes: 2
Views: 2307
Reputation: 2673
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:
EmitDefaultValue = false
property to the DataMember
attribute. This will prevent the element from being written at all in the generated xml.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).
Upvotes: 6