将对象序列化为XML

      1.首先创建一个首节点

      2.利用反射取出对象的内属性名和值

      3.在已创建的XML文档中添加该节点

     

     我们假设在对象都添加在首节点下面

public static string Serialize<T>(List<T> genericList, string rootName) { var result = new XmlDocument(); result.LoadXml("<" + rootName + "></" + rootName + ">"); foreach (T obj in genericList) { PropertyInfo[] properties = obj.GetType().GetProperties(); foreach (PropertyInfo property in properties) { if (property.GetValue(obj, null) != null) { XmlElement element = result.CreateElement(property.Name); element.InnerText = property.GetValue(obj, null).ToString(); if (result.DocumentElement != null) result.DocumentElement.AppendChild(element); } } } return result.InnerXml; }

你可能感兴趣的:(xml,properties,String,null,文档)