I have a class containing a SortedList<string, Data>
as private field, where Data
is a simple custom class with some int
, DateTime
and Nullable<DateTime>
fields.
public class CustomCollection
{
private SortedList<string, Data> _list;
...
}
Now I would make my class serializable, so I could write its content (ie the items of the _list
field) in an XML file or load data from an existing XML file.
How should I proceed?
I think I understand that there are two ways to serialize: the first would be to mark all fields as serializable, while the second would be to implement the IXmlSerializable
interface. If I understand correctly, when I can use each of the two ways?
Ok, you just need to decorate your Classes with [Serializable] attribute and it should work. However you have a SortedList which implements an IDictionary and these cant be serialized with the IXMLSerializable so need to do a bit of customization look here
but if you change your sorted list to a normal list or anything that doesnt implement an IDictionary then the below code will work :-) copy it to a console app and run it.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Data d = new Data { CurrentDateTime = DateTime.Now, DataId = 1 };
Data d1 = new Data { CurrentDateTime = DateTime.Now, DataId = 2 };
Data d2 = new Data { CurrentDateTime = DateTime.Now, DataId = 3 };
CustomCollection cc = new CustomCollection
{List = new List<Data> {d, d1, d2}};
//This is the xml
string xml = MessageSerializer<CustomCollection>.Serialize(cc);
//This is deserialising it back to the original collection
CustomCollection collection = MessageSerializer<CustomCollection>.Deserialize(xml);
}
}
[Serializable]
public class Data
{
public int DataId;
public DateTime CurrentDateTime;
public DateTime? CurrentNullableDateTime;
}
[Serializable]
public class CustomCollection
{
public List<Data> List;
}
public class MessageSerializer<T>
{
public static T Deserialize(string type)
{
var serializer = new XmlSerializer(typeof(T));
var result = (T)serializer.Deserialize(new StringReader(type));
return result;
}
public static string Serialize(T type)
{
var serializer = new XmlSerializer(typeof(T));
string originalMessage;
using (var ms = new MemoryStream())
{
serializer.Serialize(ms, type);
ms.Position = 0;
var document = new XmlDocument();
document.Load(ms);
originalMessage = document.OuterXml;
}
return originalMessage;
}
}
}