Thursday, 2 February 2012

Deserializing XML to Dynamic Object in C#

Little bit background about this blog entry – most of the applications today are driven by (BIG) settings file (usually in XML format) , this is absolutely fine and will work as expected. Let’s look at a real world scenario of XML driven applications – suppose user wants an extra feature which is controlled based on an entry in the XML settings file that means we have to handle that extra settings parameter in our application.

Not a BIG deal; we could do it in following ways
#1) if you are using a custom XML Settings parser then change it (add XPATH/read node attribute etc.) - Old fashion approach :-(.
#2) Create a new XML schema from XML and use XSD.exe to generate classes from the schema (if it simple change like adding attribute etc. then you can modify the auto generated class file directly ) ;And deserialize the XML to an object and use this object everywhere.
#3) LinqToXML

Since I came from strong OOPS background I personally prefer to use everything as objects, so obviously my choice is second one (of course I won’t generate class file from schema for every change!!! )
These patterns are good still I was looking something DYNAMIC until DotNet 4.0 released with ‘dynamic’ type support.

Let’s look at an example with ‘Dynamic’ type(these are samples so keeping it simple as possible :-) to explain the idea)

In version 1.0 of settings (config) file [application will read this settings file and set the button text – simple yaaaa ],

<?xml version="1.0" encoding="utf-8" ?>
<UISettings >
<Button Text="Show Data" />

//Code snippet
dynamic settingObject = SomeXmlToDynamicObjectParser.Parse(“Settings.xml”);
Then real beauty,
MyForm.btnData.Text = settingObject.Button.Text;

Now in version 2.0 of settings ,suppose we have added one more button setting (i.e. width)

<? version="1.0" encoding="utf-8" ?>
<Button Text="Show Data" Width="50" />

//Code snippet
dynamic settingObject = SomeXmlToDynamicObjectParser.Parse(“Settings.xml”);
MyForm.btnData.Text = settingObject.Button.Text;
MyForm.btnData.Width = double.Parse(settingObject.Button.Width); (So simple yaaa!!!!)

I started to love this pattern and applied in many BIG xml driven production applications.(This is just my view if you have a different opinion or better approach please share in comment section).

You can find the implementation of ‘SomeXmlToDynamicObjectParserHere.

Happy Coding Days ….