publicclass ConstructEntityList<T>where T : class, new() { private Type tType; private XmlDocument document =new XmlDocument(); public ConstructEntityList() { //获得要生成的列表对应的实体类型 tType =typeof(T); //加载配置文件 document.Load(@"D:\PracticeAndTeach\PracticeAndTeach\PATWebSite\Component\ListConfig.xml"); } /**////<summary> /// 获得实体列表table ///</summary> ///<param name="iqueryable">转换源</param> ///<param name="type">模板类型</param> ///<returns>table</returns> publicstring GetEntityListString(IQueryable<T> iqueryable, object type) { //得到模板的列元素 XmlNodeList list = document.SelectNodes(string.Format("/ListConfig/{0}[@type={1}]/Column",tType.Name, Convert.ToInt32(type))); StringBuilder listBuilder =new StringBuilder(); //构造table的表头,并且设置table的属性 listBuilder.AppendFormat("<table {0} ><tr>", document.SelectSingleNode(string.Format("/ListConfig/{0}[@type={1}]",tType.Name, Convert.ToInt32(type))).Attributes.GetNamedItem("attribute").Value); for (int i =0; i < list.Count; i++) { listBuilder.AppendFormat("<td {1}>{0}</td>", list.Item(i).InnerText, list.Item(i).Attributes.GetNamedItem("attribute").Value); } listBuilder.Append("</tr>"); PropertyInfo info; //遍历数据源,通过xml配置文件得到需要读取的实体属性,利用反射得到属性值 foreach (T t in iqueryable) { listBuilder.Append("<tr>"); for (int i =0; i < list.Count; i++) { info = tType.GetProperty(list.Item(i).Attributes.GetNamedItem("name").Value); listBuilder.AppendFormat("<td>{0}</td>", info.GetValue(t, null)); } listBuilder.Append("</tr>"); } listBuilder.Append("</table>"); return listBuilder.ToString(); } }
应用: 调用第一种xml配置 new ConstructEntityList<Project>().GetEntityListString((from s in patDataContext.Projects select s), ProjectList.Default); 结果: 调用第二种xml配置 new ConstructEntityList<Project>().GetEntityListString((from s in patDataContext.Projects select s), ProjectList.More); 结果: