Last active
September 19, 2016 14:19
-
-
Save alexcmd/795e50e721957f2968d8 to your computer and use it in GitHub Desktop.
Work with XML ExtendedObject
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
// Create | |
//dynamic contact = new DynamicXMLNode("Contacts"); | |
//contact.Name = "Patrick Hines"; | |
//contact.Phone = "206-555-0144"; | |
//contact.Address = new DynamicXMLNode(); | |
//contact.Address.Street = "123 Main St"; | |
//contact.Address.City = "Mercer Island"; | |
//contact.Address.State = "WA"; | |
//contact.Address.Postal = "68402"; | |
// | |
// Read | |
//var xe = XElement.Parse(something); | |
//var dxn = new DynamicXmlNode(xe); | |
//var name = dxn.people.dmitri.name; | |
public class DynamicXMLNode : DynamicObject | |
{ | |
XElement node; | |
public DynamicXMLNode(XElement node) | |
{ | |
this.node = node; | |
} | |
public DynamicXMLNode() | |
{ | |
} | |
public DynamicXMLNode(String name) | |
{ | |
node = new XElement(name); | |
} | |
public override bool TrySetMember( | |
SetMemberBinder binder, object value) | |
{ | |
XElement setNode = node.Element(binder.Name); | |
if (setNode != null) | |
setNode.SetValue(value); | |
else | |
{ | |
if (value.GetType() == typeof(DynamicXMLNode)) | |
node.Add(new XElement(binder.Name)); | |
else | |
node.Add(new XElement(binder.Name, value)); | |
} | |
return true; | |
} | |
public override bool TryGetMember( | |
GetMemberBinder binder, out object result) | |
{ | |
XElement getNode = node.Element(binder.Name); | |
if (getNode != null) | |
{ | |
result = new DynamicXMLNode(getNode); | |
return true; | |
} | |
else | |
{ | |
result = null; | |
return false; | |
} | |
} | |
public override bool TryInvokeMember( | |
InvokeMemberBinder binder, | |
object[] args, | |
out object result) | |
{ | |
Type xmlType = typeof(XElement); | |
try | |
{ | |
result = xmlType.InvokeMember( | |
binder.Name, | |
BindingFlags.InvokeMethod | | |
BindingFlags.Public | | |
BindingFlags.Instance, | |
null, node, args); | |
return true; | |
} | |
catch | |
{ | |
result = null; | |
return false; | |
} | |
} | |
public override bool TryConvert(ConvertBinder binder, out object result) | |
{ | |
if (binder.Type == typeof(String)) | |
{ | |
result = node.Value; | |
return true; | |
} | |
else | |
{ | |
result = null; | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment