首页 > 代码库 > 实体转XML XML转实体
实体转XML XML转实体
// <summary> /// 实体类序列化成xml /// </summary> /// <param name="enitities">实体.</param> /// <param name="headtag">节点名称</param> /// <returns></returns> public static string ObjListToXml<T>(List<T> enitities, string headtag) { StringBuilder sb = new StringBuilder(); System.Reflection.PropertyInfo[] propinfos = null; sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.AppendLine("<" + headtag + ">"); foreach (T obj in enitities) { //初始化propertyinfo if (propinfos == null) { Type objtype = obj.GetType(); propinfos = objtype.GetProperties(); } sb.AppendLine("<item>"); foreach (System.Reflection.PropertyInfo propinfo in propinfos) { sb.Append("<"); sb.Append(propinfo.Name); sb.Append(">"); sb.Append(propinfo.GetValue(obj, null)); sb.Append("</"); sb.Append(propinfo.Name); sb.AppendLine(">"); } sb.AppendLine("</item>"); } sb.AppendLine("</" + headtag + ">"); return sb.ToString(); } /// <summary> /// xml文件转化为实体类列表 /// </summary> /// <typeparam name="T">实体名称</typeparam> /// <param name="xml">您的xml文件</param> /// <param name="headtag">xml头文件</param> /// <returns>实体列表</returns> public static List<T> XmlToObjList<T>(string xml, string headtag) where T : new() { List<T> list = new List<T>(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Reflection.PropertyInfo[] propinfos = null; doc.LoadXml(xml); System.Xml.XmlNodeList nodelist = doc.GetElementsByTagName(headtag); foreach (System.Xml.XmlNode node in nodelist) { T entity = new T(); //初始化propertyinfo if (propinfos == null) { Type objtype = entity.GetType(); propinfos = objtype.GetProperties(); } //填充entity类的属性 foreach (System.Reflection.PropertyInfo propinfo in propinfos) { //实体类字段首字母变成小写的 string name = propinfo.Name.Substring(0, 1) + propinfo.Name.Substring(1, propinfo.Name.Length - 1); System.Xml.XmlNode cnode = node.SelectSingleNode(name); string v = cnode.InnerText; if (v != null) propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null); } list.Add(entity); } return list; }
实体转XML XML转实体
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。