1. 程式人生 > >xml檔案和DataTable之間相互轉換

xml檔案和DataTable之間相互轉換

using System.Xml;
using System.Xml.Serialization;
       /// <summary>
        /// 下面兩個方法實現xml檔案和datatable間的相互轉換
        /// </summary>
        /// <param name="strXml"></param>
        /// <returns></returns>
        public StringBuilder datatableToXml(DataTable dt) //返回stringbuilder型別
        {
            StringBuilder stb = new StringBuilder();
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            XmlWriter writer = XmlWriter.Create(stb);
            serializer.Serialize(writer, dt);
            writer.Close();
            return stb;
        }

        public DataTable xmlToDatatable(string strXml) //返回datatable型別
        {
            StringReader sr = new StringReader(strXml);
            XmlTextReader xtr = new XmlTextReader(sr);
            DataTable dt = new DataTable();
            dt.ReadXml(xtr);
            sr.Close();
            xtr.Close();
            return dt;
        }