如何將資料庫中的表導成XML檔案

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   檔案   資料   ar   

1.現將資料庫中的資訊讀到DataTable中

2.用函數將DataTable轉為string

        private string ConvertDataTableToXML(DataTable dt)        {            if (dt != null)            {                MemoryStream ms = null;                XmlTextWriter XmlWt = null;                try                {                    ms = new MemoryStream();                    XmlWt = new XmlTextWriter(ms, Encoding.Unicode);                    dt.TableName = "Table";                    /*給DataTable一個名字,隨便起一個就行,沒實際意義,但不寫會報錯*/

dt.WriteXml(XmlWt, XmlWriteMode.WriteSchema); /*WriteXml方法為.Net自己封裝的方法,不支援overwrite,但.Net提供了多種WriteXml方法,可根據自己的需求選擇,WriteXml(XmlWt, XmlWriteMode.WriteSchema)會匯出一個表頭,方便之後將xml檔案重新匯入資料庫;WriteXml(XmlWt)匯出的xml檔案不包括表頭,會出現缺列問題,如果某一列資料為null,那麼那一列會不寫*/
int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); UnicodeEncoding ucode = new UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; } catch (System.Exception ex) { throw ex; } finally { if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } }

 3.寫檔案

    public void WriteStream(string sFileName, string sContent)        {            Response.ClearContent();            Response.AddHeader("content-disposition", "attachment; filename=" + sFileName);            Response.ContentType = "text/xml";            Response.Write(sContent);            Response.End();        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.