public static T ToObject <T>(this XmlDocument doc) { Type type = typeof(T); string elementName = type.Name; XmlNode elementNode = null; ChoXPathAttribute xpathAttribute = type.GetCustomAttribute <ChoXPathAttribute>(); if (xpathAttribute == null) { XmlRootAttribute rootAttribute = type.GetCustomAttribute <XmlRootAttribute>(); elementName = rootAttribute != null ? rootAttribute.ElementName : type.Name; elementNode = doc.SelectSingleNode("//{0}".FormatString(elementName)); } else { elementNode = doc.SelectSingleNode(xpathAttribute.XPath); } if (elementNode != null) { return(elementNode.ToObject <T>()); } return(default(T)); }
public static void SaveAsChild(this XmlNode node, object target) { if (node == null) { return; } if (target == null) { return; } Type type = target.GetType(); string elementName = type.Name; XmlNode elementNode = null; ChoXPathAttribute xpathAttribute = type.GetCustomAttribute <ChoXPathAttribute>(); if (xpathAttribute == null) { XmlRootAttribute rootAttribute = type.GetCustomAttribute <XmlRootAttribute>(); elementName = rootAttribute != null ? rootAttribute.ElementName : type.Name; elementNode = node.SelectSingleNode("/{0}".FormatString(elementName)); } else { elementNode = node.SelectSingleNode(xpathAttribute.XPath); } XmlNode configNode = node.MakeXPath(elementName); if (configNode != null) { string configXml = target.ToNullNSXml(); if (configXml.IsNullOrEmpty()) { return; } ChoXmlDocument.SetOuterXml(configNode, configXml); } }