XML to ExpandoObject using Recursion in C#

Here's how to convert XML to an ExpandoObject using recursion.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static dynamic ToExpando(this XDocument document)
{
    return CreateExpando(document.Root);
}
private static dynamic CreateExpando(XElement element)
{
    var result = new ExpandoObject() as IDictionary<string, object>;
    if (element.Elements().Any(x => x.HasElements))
    {
        var list = new List<ExpandoObject>();
        result.Add(element.Name.ToString(), list);

        foreach (var childElement in element.Elements())
        {
           list.Add(CreateExpando(childElement));
        }
     }
     else
     {
         foreach (var leafElement in element.Elements())
         {
            result.Add(leafElement.Name.ToString(), leafElement.Value);
         }
      }

      return result;
}
Happy Coding!

Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

Automatically Discover and Assign Parameter with Values to a Stored Procedure Call in C#