Search code examples
c#.netserializationencapsulationxstream

C# XML Serialization - weakening encapsulation?


Am I correct in thinking that, in order to get C# to serialize an object, I MUST have a public property for every field that needs its state stored?

If so, is that not very very sucky, as it weakens (if not breaks entirely) any encapsulation my class has?

In Java, XStream can iterate over every non-transient field and archive it. In C# this can't happen, and just to make things worse, things like Dictionaries don't serialize AT ALL. It's all a bit of a mess, no?

I've seen the DLL for a "port" of XStream to .net, but there are no docs and I'm suspicious.


Solution

  • You should use DataContractSerializer, and mark every property/field you want to serialize with [DataMember]. It doesn't care if your fields are private or public. By the way you can serialize Dictionaries with it...

    [DataContract]
    public class MyClass
    {
        [DataMember]
        private string _privateField;
    
        [DataMember]
        public int PublicProperty { get; set;}
    }
    

    Serialization :

    private static string SerializeXml<T>(T item)
    {
        DataContractSerializer ser = new DataContractSerializer(item.GetType());
    
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment };
        using (XmlWriter writer = new XmlWriter(sb, settings))
        {
            ser.WriteObject(writer, item);
        }
        return sb.ToString();
    }
    

    Look here for differences between XmlSerializer and DataContractSerializer : http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/