Wednesday, June 4, 2008

C# Converting a Class to XML

Using a class in C# to hold data is the right idea. XML is just a transport mechanism and should only be used at the boundaries of your application. So, as soon as you grab a chunk of XML from somewhere you should turn it into a class. Similarly, when you want to send some data somewhere, encapsulate the data in a class, and then serialise the class to XML. This way, if you decide to get rid of XML and use INI files, or CSV files, or YAML files then you don't need to change your core application - you only change the routines that serialise and deserialise the class.

Q. How to easily turn a class into XML?

A. For a simple class setup, you only need about four lines of code. For a user-defined class called "cls":


XmlSerializer serializer = new XmlSerializer(cls.GetType());
StringWriter writer = new StringWriter();
serializer.Serialize(writer, cls);
string xml = writer.GetStringBuilder().ToString();

No comments: