nbjkj的心得小站

导航

XML字符串转换为实体泛型列表数据

        /// <summary>
/// 把XML字符串转换为LIST用于存储数据
/// </summary>
/// <typeparam name="T">任意实体类</typeparam>
/// <param name="XML">XML字符串</param>
/// <param name="tableName">表名</param>
/// <returns></returns>
public static List<T> ConvertXMLToList<T>(string XML, string tableName) where T : new()
{
//利用反射获得实体类的属性
List<T> list = new List<T>();

XML = XML.Replace("NewDataSet", "data");
XDocument output = XDocument.Parse(XML);
XElement root = output.Root;

foreach (XElement elem in root.Elements(tableName))
{
T RowInstance = Activator.CreateInstance<T>();
foreach (PropertyInfo Property in typeof(T).GetProperties())
{
if (elem.Element(Property.Name) != null)
{
Property.SetValue(RowInstance, Convert.ChangeType(elem.Element(Property.Name).Value.Trim(), Property.PropertyType), null);
}
}
list.Add(RowInstance);
}
return list;
}

XML字符串通过WEB SERVICE 的DATASET的GetXml方法获取,接下来就创建这个表的实体类,最后调用这个方法获得泛型列表。

编辑器加载中...

posted on 2012-01-16 09:11  nbjkj  阅读(535)  评论(0编辑  收藏  举报