Last active
August 29, 2015 13:56
-
-
Save jlyonsmith/8929274 to your computer and use it in GitHub Desktop.
ExpandoObjectHelper
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
using System; | |
using System.Collections.Generic; | |
using System.Dynamic; | |
using System.Linq; | |
using System.Xml.Linq; | |
namespace ToolBelt.Dynamic | |
{ | |
// | |
// This class came from http://www.codeproject.com/Articles/461677/Creating-a-dynamic-object-from-XML-using-ExpandoOb | |
// | |
// The original in the article had bugs and was way more code than was needed to get the job done. | |
// | |
public static class ExpandoObjectHelper | |
{ | |
public static void ParseXmlToDynamic(dynamic obj, XElement element, IList<string> knownLists = null) | |
{ | |
var childElements = element.Elements(); | |
foreach (var childElement in childElements) | |
{ | |
string elementName = childElement.Name.LocalName; | |
if (childElement.HasElements) | |
{ | |
if (knownLists != null && knownLists.Contains(elementName)) | |
{ | |
var list = new List<dynamic>(); | |
foreach (var listElement in childElements) | |
{ | |
var listObj = new ExpandoObject(); | |
ParseXmlToDynamic(listObj, listElement, knownLists); | |
list.Add(listObj); | |
} | |
AddProperty(obj, elementName, list); | |
} | |
else | |
{ | |
var childObj = new ExpandoObject(); | |
ParseXmlToDynamic(childObj, childElement, knownLists); | |
AddProperty(obj, elementName, childObj); | |
} | |
} | |
else | |
{ | |
AddProperty(obj, elementName, element.Value.Trim()); | |
} | |
} | |
foreach (var attribute in element.Attributes()) | |
{ | |
AddProperty(obj, attribute.Name.LocalName, attribute.Value.Trim()); | |
} | |
} | |
private static void AddProperty(dynamic parent, string name, object value) | |
{ | |
if (parent is List<dynamic>) | |
{ | |
(parent as List<dynamic>).Add(value); | |
} | |
else | |
{ | |
(parent as IDictionary<string, object>)[name] = value; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment