C# DataTable 转 XML

版权声明:转载需注明出处 https://blog.csdn.net/w529409399/article/details/80103189

每一行DataRow转为一个detail标签。

DataRow中每一列又转为一个子标签,标签名称即为列名。

T是泛型,传入实体类,该类中的每个属性字段对应DataRow中的每一列的列名,且每个属性必须有{ get; set; } ,且必须为公共属性。


using System.Data;
using System.Reflection;

public string DataTableToXML<T>(DataTable dt)
    {
        string result = "";
        T obj = default(T);
        // 定义集合    
        IList<T> ts = new List<T>();

        // 获得此模型的类型   
        Type type = typeof(T);
        string tempName = "";

        foreach (DataRow dr in dt.Rows)
        {
            result += "<detail>";
            obj = Activator.CreateInstance<T>();
            // 获得此模型的公共属性      
            PropertyInfo[] propertys = obj.GetType().GetProperties();
            foreach (PropertyInfo pi in propertys)
            {
                tempName = pi.Name;  // 检查DataTable是否包含此列    
                result += "<"+tempName+">";
                if (dt.Columns.Contains(tempName))
                {
                    object value = dr[tempName];
                    if (value != DBNull.Value)
                        result += value.ToString().Trim();
                }
                result += "</" + tempName + ">";
            }
            result += "</detail>";
        }

        return result;
    }

猜你喜欢

转载自blog.csdn.net/w529409399/article/details/80103189
今日推荐