Skip to content

Instantly share code, notes, and snippets.

@xeb
Created February 1, 2014 00:58
Show Gist options
  • Save xeb/8746403 to your computer and use it in GitHub Desktop.
Save xeb/8746403 to your computer and use it in GitHub Desktop.
DynamicXml
public class DynamicXml : DynamicObject
{
XElement _root;
private DynamicXml(XElement root)
{
_root = root;
}
public static DynamicXml Parse(string xmlString)
{
return new DynamicXml(XDocument.Parse(xmlString).Root);
}
public static DynamicXml Load(string filename)
{
return new DynamicXml(XDocument.Load(filename).Root);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
var att = _root.Attribute(binder.Name);
if (att != null)
{
result = att.Value;
return true;
}
var nodes = _root.Elements(binder.Name);
if (nodes.Count() > 1)
{
result = nodes.Select(n => new DynamicXml(n)).ToList();
return true;
}
var node = _root.Element(binder.Name);
if (node != null)
{
if (node.HasElements)
{
result = new DynamicXml(node);
}
else
{
result = node.Value;
}
return true;
}
return true;
}
}
@xeb
Copy link
Author

xeb commented Feb 1, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment