/// <summary>输出列表类型数据</summary> private void WriteList(StringBuilder sb, object obj) { foreach (var item in (obj as IEnumerable)) { var node = SerializationNode.FromType(item.GetType()); // 无论简单类型还是复杂类型,列表元素输出都要加上类型名。格式如:<Person>...</Person> or <String>...</String> sb.AppendFormat("<{0}>", node.Name); WriteInner(sb, item, ""); sb.AppendFormat("</{0}>", node.Name); } }
/// <summary>将xml解析为集合</summary> private IList ParseNodeToList(XmlNode node, Type type) { var tag = SerializationNode.FromType(type); var list = Activator.CreateInstance(type) as IList; var nodes = node.SelectNodes(tag.ItemType.Name); foreach (XmlNode subNode in nodes) { var item = ParseNode(subNode, tag.ItemType); list.Add(item); } return(list); }
/// <summary>将xml解析为字典</summary> /// <remarks> /// 格式如: /// <Persons> /// <Kevin>...</Kevin> /// <Willion>.....</Willion> /// </Persons> /// </remarks> private object ParseNodeToDict(XmlNode node, Type type) { var tag = SerializationNode.FromType(type); var dict = Activator.CreateInstance(type) as IDictionary; var nodes = node.ChildNodes; foreach (XmlNode subNode in nodes) { var key = XmlTagDecode(subNode.Name); var item = ParseNode(subNode, tag.ItemType); dict.Add(key, item); } return(dict); }
/// <summary>将xml解析为数组</summary> private object ParseNodeToArray(XmlNode node, Type type) { var tag = SerializationNode.FromType(type); var nodes = node.SelectNodes(tag.ItemType.Name); Array array = Array.CreateInstance(type, nodes.Count); var collection = Convert.ChangeType(array, type); int index = 0; foreach (XmlNode subNode in nodes) { var item = ParseNode(subNode, tag.ItemType); SetItemValue(collection, item, index++); } return(collection); }
/// <summary>解析 XML 字符串为对象(请自行捕捉解析异常)</summary> public object Parse(string xml, Type type) { // 简单值类型直接解析 var node = SerializationNode.FromType(type); if (node.Type == SerializationType.Basic) { return(xml.ParseBasicType(type)); } // 复杂类型再解析ML var doc = new XmlDocument(); doc.LoadXml(xml); return(ParseNode(doc.DocumentElement, type)); }
/// <summary>将XML节点解析为指定类型的对象</summary> object ParseNode(XmlNode node, Type type) { var tag = SerializationNode.FromType(type); if (tag.Type == SerializationType.Basic) { return(ParseNodeToValue(node, type)); } if (tag.Type == SerializationType.List) { return(ParseNodeToList(node, type)); } if (tag.Type == SerializationType.Array) { return(ParseNodeToArray(node, type)); } if (tag.Type == SerializationType.Dict) { return(ParseNodeToDict(node, type)); } return(ParseNodeToObject(node, type)); }