Practical Use of Expando Object in CSharp

I am going to parse the below Person information in a XML file and Pull out the FirstName of each employee. There is a couple of way to do this .One way is by using Linq To XML like below

<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<FirstName>Jameel</FirstName>
</Person>
<Person>
<FirstName>Sreeraj</FirstName>
</Person>
<Person>
<FirstName>Vinayan</FirstName>
</Person>
<Person>
<FirstName>Anuraj</FirstName>
</Person>
<Person>
<FirstName>Niju</FirstName>
</Person>
</Persons>


private static void Main(string[] args)
{
var document = XDocument.Load("PersonDetails.xml");
var xElement = document.Element("Persons");
if (xElement != null)
foreach (var item in xElement.Elements("Person"))
{
var element = item.Element("FirstName");
if (element != null) Console.WriteLine(element.Value);
}
}

But it is little bit cluttered code. Let us try this same thing by using expando

var doc = XDocument.Load("PersonDetails.xml").AsExpando();
foreach (var person in doc.Persons)
{
Console.WriteLine(person.FirstName);
}

AsExpando is an extension method which create object graphs based on XDocument elements.You can reuse this method in this scenarios.

public static  class ExpandoXml
{
public static dynamic AsExpando(this XDocument xDocument)
{
return CreateExpando(xDocument.Root);
}


private static dynamic CreateExpando(XElement xElement)
{
var result = new System.Dynamic.ExpandoObject() as IDictionary<string, object>;
if(xElement.Elements().Any(x=>x.HasElements))
{
var list = new List<System.Dynamic.ExpandoObject>();
result.Add(xElement.Name.ToString(),list);
foreach (var childElement in xElement.Elements())
{
list.Add(CreateExpando(childElement));
}
}
else
{
foreach (var leafElement in xElement.Elements())
{
result.Add(leafElement.Name.ToString(),leafElement.Value);
}
}
return result;
}
}

Enjoy Programming..

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