/// <summary> /// 访问xml中对象集合 /// </summary> /// <param name="xml"></param> /// <returns></returns> private T VisitXmlGeneric(string xml) { T collection = Activator.CreateInstance <T>(); List <string> xmlArr = XmlTagHelper.GetTagContents(xml, _rootTag, "", _needCData); foreach (var itemXml in xmlArr) { AddElement(collection, itemXml, obj => { Add(collection, obj); }); } return(collection); }
/// <summary> /// 访问xml中对象集合 /// </summary> /// <param name="xml"></param> /// <returns></returns> private T VisitXmlArray(string xml) { List <string> xmlArr = XmlTagHelper.GetTagContents(xml, _rootTag, "", _needCData); Array array = Array.CreateInstance(_elementType, xmlArr.Count); T collection = (T)Convert.ChangeType(array, typeof(T)); int index = 0; foreach (var itemXml in xmlArr) { AddElement(collection, itemXml, obj => { SetValue(collection, obj, index++); }); } return(collection); }
/// <summary> /// 对象序列化为xml /// </summary> /// <param name="xml"></param> /// <param name="obj"></param> /// <param name="fields"></param> private void VisitXml(string xml, object obj, PropertyInfo[] fields) { foreach (var field in fields) { string subXml = XmlTagHelper.GetSubXmlContent(xml, field.Name.FirstToLower(), ""); Type subType = field.PropertyType; if (!subType.FullName.StartsWith("System.") && !IsEnumType(subType)) { object subObj = Activator.CreateInstance(subType);// field.GetValue(obj); var subFields = subType.GetProperties(BindingFlags.Public | BindingFlags.Instance); field.SetValue(obj, subObj); if (subFields.Count() > 0) { VisitXml(subXml, subObj, subFields); } else { field.SetValue(subObj, XmlTagHelper.GetTagContent(subXml, field.Name.FirstToLower(), "", _needCData)); } } else { var value = XmlTagHelper.GetTagContent(subXml, field.Name.FirstToLower(), "", _needCData); if (subType != typeof(string)) { if (IsEnumType(subType)) { field.SetValue(obj, Enum.Parse(subType, value)); } else { field.SetValue(obj, Convert.ChangeType(value, subType)); } } else { field.SetValue(obj, value); } } } }