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 bar and barSpecified in code above. If barSpecified is not set to 'true', bar property will not be serialized. It's XMLSerializer's way of saying that bar is kind of NULL and shouldn't be serialized.
There are at least 3 possibilities for solving that:
-removing barSpecified property and field
-setting barSpecified to 'true'
-if class implements INotifyPropertyChanged make usage of it (if class is autogenerated it's good to make it as partial class in another file like below):
public partial class Foo
{
public Foo()
{
this.PropertyChanged += (object sender, System.ComponentModel.PropertyChangedEventArgs e) =>
{
if (!e.PropertyName.EndsWith("Specified"))
{
var prop = this.GetType().GetProperty(e.PropertyName + "Specified");
if (prop != null)
prop.SetValue(this, true, null);
}
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With