Skip to content

Instantly share code, notes, and snippets.

@SneakyBrian
Created October 5, 2012 17:34
Show Gist options
  • Save SneakyBrian/3841195 to your computer and use it in GitHub Desktop.
Save SneakyBrian/3841195 to your computer and use it in GitHub Desktop.
Get A Dynamic Object from an xml file
private static dynamic GetDynamicFromXml(string pathToXml)
{
var xdoc = XDocument.Load(pathToXml);
return GetDynamicFromNode(xdoc.Root);
}
private static dynamic GetDynamicFromNode(XElement node)
{
dynamic result = new ExpandoObject();
foreach (var elementGroup in node.Elements().GroupBy(n => n.Name.LocalName))
{
var resultDictionary = (IDictionary<String, dynamic>)result;
var values = new List<dynamic>();
foreach (var element in elementGroup)
{
values.Add((element.HasElements) ? GetDynamicFromNode(element) : element.Value.Trim());
}
resultDictionary[elementGroup.Key] = elementGroup.Count() > 1 ? values : values.FirstOrDefault();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment