Articles

Using ExpandoObject (Dynamic) with XML data

In C# on 2011/11/20 by phejndorf

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("http://phejndorf.wordpress.com/feed/", "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!

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: