Serializing private member data
To serialize private member data use DataContractSerializer follow the codes given, but cannot able to use xml attributes and only xml elements,
using System; using System.Runtime.Serialization; using System.Xml; [DataContract] class MyObject { public MyObject(Guid id) { this.id = id; } [DataMember(Name="Id")] private Guid id; public Guid Id { get {return id;}} } static class Program { static void Main() { var ser = new DataContractSerializer(typeof(MyObject)); var obj = new MyObject(Guid.NewGuid()); using(XmlWriter xw = XmlWriter.Create(Console.Out)) { ser.WriteObject(xw, obj); } } }
Also can implement IXmlSerializable and can do everything – but this works with XmlSerializer.
Use the System.Runtime.Serialization.NetDataContractSerializer. It is powerful and will fix some affair of the classic Xml Serializer. There are different attributes for this,
[DataContract] public class X { [DataMember] public Guid Id { get; private set; } } NetDataContractSerializer serializer = new NetDataContractSerializer(); TextWriter tw = new StreamWriter(_location); serializer.Serialize(tw, obj);
So, possibly use System.Runtime.Serialization.DataContractSerializer for the case to get a clean XML. and the other codes is the same.
While using the XmlSerializer, the read only fields will not be serialized, that is due to the nature of the readonly keyword
From MSDN:
The keyword readonly is a modifier that can be used on the fields. When a field declaration that includes a readonly modifier, assignments to the fields imported by the declaration will only occur as a part of the declaration or in a constructor in the same class. So, there is much need to set the fields value in the default constructor.
public void SaveMyObject(MyObject obj)
{
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
TextWriter tw = new StreamWriter(_location);
serializer.Serialize(tw, obj);
tw.Close();
}
using System;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
class MyObject {
public MyObject(Guid id) { this.id = id; }
[DataMember(Name="Id")]
private Guid id;
public Guid Id { get {return id;}}
}
static class Program {
static void Main() {
var ser = new DataContractSerializer(typeof(MyObject));
var obj = new MyObject(Guid.NewGuid());
using(XmlWriter xw = XmlWriter.Create(Console.Out)) {
ser.WriteObject(xw, obj);
}
}
}
[DataContract]
public class X
{
[DataMember]
public Guid Id { get; private set; }
}
NetDataContractSerializer serializer = new NetDataContractSerializer();
TextWriter tw = new StreamWriter(_location);
serializer.Serialize(tw, obj);
public class Data : MarshalByRefObject { private Datum m_datum; public void Copy(Data d) { this.m_datum = d.m_datum; } } [Serializable] public class Datum { ... }