Created
February 1, 2014 00:58
-
-
Save xeb/8746403 to your computer and use it in GitHub Desktop.
DynamicXml
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From: http://stackoverflow.com/questions/13704752/deserialize-xml-to-object-using-dynamic thanks L.B.!