简体   繁体   中英

Why does XMLSerializer take DefaultValue Attribute of base class to serialize

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM