Using ExpandoObject (Dynamic) with XML data

Having played with the ExpandoObject as a container for SQL data in a previous post, I’ve been playing a bit with using it for XML data which can be even more dynamic in nature.

Without further ado, here is a method that will do exactly that:

public static IEnumerable<dynamic> GetExpandoFromXml(string file, string descendantid) { var expandoFromXml = new List<dynamic>(); var doc = XDocument.Load(file); var nodes = doc.Root.Descendants(descendantid); foreach (var element in doc.Root.Descendants(descendantid)) { dynamic expandoObject = new ExpandoObject(); var dictionary = expandoObject as IDictionary<string, object>; foreach (var child in element.Descendants()) { if (child.Name.Namespace == "") dictionary[child.Name.ToString()] = child.Value.Trim(); } yield return expandoObject; } }


Note that I use a descendantid parameter to specify what part of my XML I want to fetch as dynamic objects.

In my example I was working with an RSS feed, and this is the reason why I ignore the elements that have an empty namespace, and BTW the file parameter can be an URL as well as you can see in the sample.

As I sample, I can get the “item” elements from the RSS feed of this blog like so:

var expandolist = GetExpandoFromXml("", "item");

expandolist.ToList().ForEach(element => Console.WriteLine(element.title));


Or perhaps, a bit more exotically, to list all the properties of each dynamic element:

expandolist.ToList().ForEach(element => 
    var dictionary = element as IDictionary<string, object>;
    dictionary.ToList().ForEach(d => Console.WriteLine("{0}: {1}",d.Key,d.Value));

And that’s all there is to it!

Posted in C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s