I started looking on the Internet to find an straightforward way of loading in an xml file and converting it to an object on the fly. my goal was to dynamically load setting files in xml format for a web project I'm working on.
As the definition of the xml schema is very different per setup I tough of using the dynamic keyword to load an xml document and access it as a simple object. After some browsing I found some examples that used the ExpandoObject. unfortunately they all either write about converting an object to xml or how to use XML-to-LINQ to map a specific dynamic class/object.
So I ended up writing a small recursive method that loads an xml document and converts it to a simple object.
private static dynamic _getExpandoFromXml(String file, XElement node = null)
if (String.IsNullOrWhiteSpace(file) && node == null) return null;
var doc = XDocument.Load(file);
node = doc.Root;
dynamic result = new ExpandoObject();
foreach (var gn in node.Elements())
var skip = false;
skip = (from a in gn.Attributes()
where a.Name.LocalName.ToLower() == "type"
select a.Value.ToLower()).FirstOrDefault() == "list" ? true :
gn.Elements().GroupBy(n => n.Name.LocalName).Count() == 1;
var p = result as IDictionary<String, dynamic>;
var values = new List<dynamic>();
foreach (var item in gn.Elements())
values.Add((item.HasElements) ? _getExpandoFromXml(null, item) :
values.Add((gn.HasElements) ? _getExpandoFromXml(null, gn) :
p[gn.Name.LocalName] = skip ? values : values.FirstOrDefault();
dynamic license = _getExpandoFromXml('path to xml file');
var registeredUser = license.RegisteredUser;
var companyName = license.Company;
var sites = license.Sites;
foreach(var site in sites)
var host = site.Host;
One thing that is important to realize is that this is a very simple example and is by no means full-proof. The code as it is would be useful in cases where you have control over the XML files that are provided. Also the use of dynamic has some performance issues as internally it will need to do a lot of reflection during run time and you will also loose out on error checking of the dynamic objects during compiling.
It could be useful for example to read in a configuration file or a simple list of products.