using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;
namespace SerializerTest {
static class Program {
static void Main() {
using (TextWriter textWriter = new StreamWriter("data.xml")) {
Data data = new Data();
new XmlSerializer(typeof(Data)).Serialize(textWriter, data);
textWriter.Close();
}
using (TextWriter textWriter = new StreamWriter("exData.xml")) {
ExData exData = new ExData();
new XmlSerializer(typeof(ExData)).Serialize(textWriter, exData);
textWriter.Close();
}
}
}
public class Data {
[DefaultValue(10)] public int A { get; set; }
public Data() { A = 10; }
}
public class ExData : Data {
[DefaultValue(20)] public new int A { get; set; }
public ExData() { A = 20; }
}
}
While the first serialization is as i expect (non-serialization of default value):
<?xml version="1.0" encoding="utf-8" ?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
the second results in:
<?xml version="1.0" encoding="utf-8"?>
<ExData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<A>20</A>
</ExData>
Obviously XmlSerializer takes the default value of the base class instead of taking the new one. Overiding a virtual property with "override" gives the same result. Changing the initialization of ExData's property A to 10 results in not serializing this property as if the default value of the base class property is applied. Can anybody explain this behaviour to me? Does anybody know a work around to this?
My aim is to non-serialize default values but changing default value for a derived class.