Hi Roman Wagner/ Marc Gravell,
Many thanks for your replies.
I should not have written "missing". Actually, It's an empty
element.
As you said, i can use setter method to control the value. However,
i've a problem in that.
If the element is missing, then XmlSerializer tries to set the
default values (0 for int, false for bool) to the properties. Actually,
i should get "null" value if the element is passed as empty.
If i pass the empty element, the CLR throws exception in case if the
elment corresponds to types like int or bool.
More over i wanted to have null values for all the elements which
are sent as empty elements. The class can have any type of properties
like int, bool or another type of class. Since i wanted to have null
for all the properties which are sent as empty elements, i used
nullable types for primitive types like int? (for int).
The problem happens when the XmlSerializer tries to create the
object. Since the empty element is not the correct value for int? type,
it throws error even before coming to the setter method only.
Marc, by saying i need to implement IXmlSerializable, do you mean i
mean i need to implement the interface for all the entities(classes) i
need to crate from XML? It would not be ideal as i've to create many
classes from XML.
Thanks,
Kumar
Marc Gravell wrote:
Actually the XmlSerializer assigns "" (empty string) for a string
if the corresponding element is missing in the XML.
"Missing" is very different to "empty"; your B is empty, not missing.
Anyway, no: it doesn't; first it initialises the class using the field
initialisers and the default ctor. Then it applies all the *found* items,
else applies the [DefaultValue] (if one) to any that were omitted. If it
isn't in the xml it isn't set, so it would remain null. I guess your *real*
class is initialising it to "", or the data is in the xml.
If you really want to turn an *included* (blank) <B></Bto a null, then:
If *all* "" values should become null you could simply use a property setter
of the form {...set {b = value == "" ? null : value;}}. Almost an inverse
coalesce...
If this only applies during desrialization, well, for binary serialization
you could hook some combination of [OnDeserializing], [OnDeserialized] and
IDeserializationCallback... but xml is trickier... you could possibly
implement IXmlSerializable, but this isn't trivial.
Marc