{
private int _type;
private int _goodid;
private int _number;
private string _name;
private decimal _price;
{
get { return _name; }
set { _name = value; }
}
{
get { return _type; }
set { _type = value; }
}
{
get { return _goodid; }
set { _goodid = value; }
}
{
get { return _number; }
set { _number = value; }
}
{
get { return _price; }
set { _price = value; }
}
}
/// <summary>
/// 实体类序列化成xml
/// </summary>
/// <param name="enitities">The enitities.</param>
/// <param name="headtag">The headtag.</param>
/// <returns></returns>
public static 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();
}
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("</item>");
}
sb.AppendLine("</" + headtag + ">");
return sb.ToString();
}
/// 使用XML初始化实体类容器
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="typename">The typename.</param>
/// <param name="xml">The XML.</param>
/// <param name="headtag">The 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;
}
}
使用如下:
{
OrderGoodInfo good1 = new OrderGoodInfo();
good1.GoodId = 1;
good1.Number = 1;
good1.Price = 100;
good1.Type = 1;
good2.GoodId = 2;
good2.Number = 2;
good2.Price = 200;
good2.Type = 2;
list.Add(good1);
list.Add(good2);
string xmlstr = XmlHelper.ObjListToXml(list, "goods");
Response.Write(xmlstr);
}