2013年9月10日 星期二

序列化DataTable為XML格式,將XML反序列化還原回DataTable


        #region 序列化、反序列化 DataTable
        public static string SerializeDataTableXml(DataTable dt)
        {
            //序列化DataTable為XML格式
            StringBuilder sb = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(sb);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            serializer.Serialize(writer, dt);
            writer.Close();
            return sb.ToString();
        }
        public static DataTable DeserializeDataTable(string xml)
        {
            //將XML反序列化還原回DataTable
            StringReader strReader = new StringReader(xml);
            XmlReader xmlReader = XmlReader.Create(strReader);
            XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
            DataTable dt = serializer.Deserialize(xmlReader) as DataTable;
            return dt;
        }
        #endregion
****************************************************************************************
        protected void Page_Load(object sender, EventArgs e)
        {
            //執行SQL Command命令 - 依語法查詢結果,並序列化DataTable為XML格式
            string query = null;
            DataTable dt = null;
            if (Request["Query"] != null)
            {
                try
                {
                    query = Server.UrlDecode(Request["Query"].ToString());
                    dt = Common.ExecuteReader(query, Common.trConn);
                    if (dt != null)
                    {
                        dt.TableName = "tempTable";  //這個記得要設,不然會出錯
                        //dt.WriteXml(@"D:\WEB\TicketToOutsideWeb\temp.xml");
                        //序列化DataTable為XML格式
                        string result = Common.SerializeDataTableXml(dt);
                        Response.Write(result);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.ToString());
                }
            }
            Response.End();
        }

沒有留言:

張貼留言