views:

414

answers:

1
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"&gt;
  <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.

A: 

The XmlSerializer seems to get only the first DefaultValueAttribute and I unfortunately think there's no direct workaround to what you need. You can however implement IXmlSerializable and do that kind stuff yourself.

Julien Lebosquain
Not a good alternative. Especially since this bug is class independant and an IXMLSerializable implementation would be not. Is it possible to override XMLSerializer instead without rewriting everything?
Ingo