public class ObjectXML
{
public string ObjListToXml<T>(List<T> enitities, string headtag)
{
StringBuilder sb = new StringBuilder();
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("<table name = \"Message\">");
// sb.AppendLine("<Row operation =\"Create\">");
sb.AppendLine("<item>");
foreach (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("</Row>");
// sb.AppendLine("</table>");
sb.AppendLine("</item>");
}
sb.AppendLine("</" + headtag + ">");
return sb.ToString();
}
/// <summary>
/// 从XML转化成实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <param name="headtag"></param>
/// <returns></returns>
public static List<T> XmlToObjList<T>(string xml, string headtag)
where T : new()
{
List<T> list = new List<T>();
XmlDocument doc = new XmlDocument();
PropertyInfo[] propinfos = null;
doc.LoadXml(xml);
XmlNodeList nodelist = doc.SelectNodes("/" + headtag + "/item");
foreach (XmlNode node in nodelist)
{
T entity = new T();
//初始化propertyinfo
if (propinfos == null)
{
Type objtype = entity.GetType();
propinfos = objtype.GetProperties();
}
//填充entity类的属性
foreach (PropertyInfo propinfo in propinfos)
{
XmlNode cnode = node.SelectSingleNode(propinfo.Name);
string v = cnode.InnerText;
if (v != null)
propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
}
list.Add(entity);
}
return list;
}
}