Having class code autogenerated by WCF/svcutil.exe like that:
public class Foo
{
private float barField;
bool barFieldSpecified;
public float bar
{
get
{
return this.barField;
}
set
{
this.barField = value;
}
}
[System.Xml.Serialization.SoapIgnore]
public bool barSpecified
{
get
{
return this.barFieldSpecified;
}
set
{
this.barFieldSpecified = value;
}
}
}
and using XMLSerializer like that:
Foo foo = new Foo();
foo.bar = 100;
var ser = new XmlSerializer(typeof(Foo));
var ms = new MemoryStream();
ser.Serialize(ms, foo);
var str = Encoding.UTF8.GetString(ms.ToArray());
I get XML with values in all nodes set to ‘false’ and none of my class properties I set.
The reason of such behaviour is that XMLSerializer make usage of these additional properties ending with ‘Specified’ keyword for value-typed properties like
barandbarSpecifiedin code above. IfbarSpecifiedis not set to ‘true’,barproperty will not be serialized. It’s XMLSerializer’s way of saying thatbaris kind of NULL and shouldn’t be serialized.There are at least 3 possibilities for solving that:
-removing
barSpecifiedproperty and field-setting
barSpecifiedto ‘true’-if class implements
INotifyPropertyChangedmake usage of it (if class is autogenerated it’s good to make it as partial class in another file like below):