Parsing an xml to get a c# object with dynamic type

Okay, okay you’re right, thank you Leo 😉 So let’s render unto Caesar the things which are Caesar’s… Microsoft took into account the power of those weakly-typed languages such as JavaScript, the ones which allow you to deal with types you don’t know yet. Within .NET 4, they release the dynamic type, in reference to those languages, which they specifically call dynamic languages.

So now, if you derive from DynamicObject to create your own one, you can use pretty much the same code I used previously in JavaScript to get a c# object from Xml. You can create any property you’d like at runtime, only by accessing it like an array. Just write myDynamic[“house”]=whatever and it gets created in the meantime. In the end, you’ll be able to access any property you created in a totally transparent manner like….

Plus, with the

TryConvert(ConvertBinder binder, out object result)

you can get the statically typed object you were expecting if you ever need a strongly typed object.

Enough of this talking, here you can find some more explanations about dynamic and how to take advantage of it :

and here’s the code:


Parsing an xml to get a javascript object

Parsing an xml with JavaScript to get the information you want is pretty easy. But parsing any xml to dynamically get exactly the equivalent plain JavaScript object may require a little algorithm. So you’re going to deal with a little of reflection, which is pretty easy with a weakly-typed language such as JavaScript, and you wanna build a recursive function to loop through your xml tree.
As I didn’t find a generic method on the web to get a JavaScript object from an xml, I built my own little method. So, if you’re in the same situation, here’s the code now :
Continue reading “Parsing an xml to get a javascript object”