Created
October 5, 2012 17:34
-
-
Save SneakyBrian/3841195 to your computer and use it in GitHub Desktop.
Get A Dynamic Object from an xml file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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