This time, I wanted to share a cool mechanism for handling object presentation between object instance and XML file. This mechanism can be found in System.Xml.Serialization namespace. In short, when using XmlSerializer we can create object instance directly from XML file and store object blueprint information to XML file to be used whenever needed.
Real-life design scheme
Assume we have some state-of-the-art analytic calculation engine, into which we feed a lot of different transactions and market scenario data in the first place. When the engine is up and running, we can simply give any specific calculation task object to be processed for this engine. One Task object will simply define a specific set of parameters, such as
- Calculation task name
- What kind of transactions will be selected?
- In what kind of market scenario those selected transactions will be valued?
- What kind of output values will be calculated for each transaction?
Obviously, the beef is really in handling all required configuration parameters for all calculation tasks in an efficient manner. For this purpose, we need to be able to create calculation task instances from some source. Blueprints for all task objects can be stored into XML files, from which the actual objects are going to be created by XmlSerializer to be processed by the engine.
Bridge over troubled water
For the purposes mentioned above, I came up with an idea of generic ObjectXMLHandler<T> class for handling Object/XML transformations for any type of object, not only for Task object which has been used in this example. Behind the scenes, this class is nothing more but a wrapper for XmlSerializer, which can create (store) a list of objects from (to) XML files.
For storing object blueprints into XML file (Serialize), the class client will give a list of object instances, a list of file names to be used and a path name for a specific target folder. Below is a screenshot of one Task object blueprint XML file, created by ObjectXMLHandler.
For creating objects from XML file (Deserialize), the class client will only give a path name for a specific target folder, in which all object blueprints are stored in XML files. When calling this method, the class will return a list of object instances (having type of T) for its client. Below is a screenshot of all three Task object instances which have been created from XML files by ObjectXMLHandler.
Personally, I find XmlSerialization class to be extremely useful for the schemes like the one presented in here. It will completely liberate me from writing my own XML handlers for such cases.
A small dark cloud within this overwhelming joy is the fact, that this presented XmlSerializer class can only handle member data which has been defined to be public. For other cases, I would recommend to dig deeper into implementing IXmlSerializable interface, found in the same namespace.
Thanks for reading my blog. I hope you have got some useful ideas for your own programs.