using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ListToXml
{
/// <summary>
/// 将泛型转化为 XML文本
/// </summary>
class Program
{
static void Main(string[] args)
{
List<ItemID> list = new List<ItemID>()
{
new ItemID(){ ID = 1, Name = "Zbjuke"},
new ItemID(){ ID = 2, Name = "Ting"}
};
string str = beanListToXml<ItemID>(list);
Console.WriteLine(str);
}
public static string beanListToXml<T>(object objecList)
{
List<T> list = objecList as List<T>;
string retrunValue = "";
try
{
if (list != null)
{
StringBuilder sbXml = new StringBuilder();
sbXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").Append("\r\n");
string className = typeof(T).Name;
sbXml.AppendFormat("<{0}List>", className).Append("\r\n");
foreach (T t in list)
{
sbXml.AppendFormat("<{0}>", className).Append("\r\n");
PropertyInfo[] prolist = t.GetType().GetProperties();
foreach (PropertyInfo p in prolist)
{
sbXml.AppendFormat("<{0}>{1}</{0}>", p.Name, p.GetValue(t, null)).Append("\r\n");
}
sbXml.AppendFormat("</{0}>", className).Append("\r\n");
}
sbXml.AppendFormat("</{0}List>", className);
retrunValue = sbXml.ToString();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
retrunValue = "error";
}
return retrunValue;
}
}
/// <summary>
///
/// </summary>
public class ItemID
{
public int ID { get; set; }
public string Name { get; set; }
}
}