Saturday 24 March 2012

Surface project - part 11(C# Object to XML and vice versa)

The task in this week is to extend the custom media tag browser here to add multiple media file into one push pin. The idea is fairly easy, as the surface list box is general enough to composite any framework element as an item, the remain problem is how to persist the pushpin into local file. The supersivors preferred to store the pushpin into XML file. After look into the MSDN, I found that .net already provides a very flexible and powerful mechanism to serialize object into XML file and vice versa.

As the object, which represents the push pin, only contains string and double fields. To mark the object as [Serializable] is enough.

Following examples demonstrate the basic coding. The full example can be found here.

How to serialize object to XML

string path = "MySettings.xml";
XmlSerializer x = new XmlSerializer(settings.GetType());
StreamWriter writer = new StreamWriter(path);
x.Serialize(writer, settings);

How to deserialize XML back to object

MySettings settings = new MySettings();
string path = "MySettings.xml";
XmlSerializer x = new XmlSerializer(typeof(MySettings));
StreamReader reader = new StreamReader(path);
settings = (TVSettings)x.Deserialize(reader);

No comments:

Post a Comment