使用WriteXml,ReadXml序列化還原序列化DataTable

來源:互聯網
上載者:User

標籤:序列化和還原序列化

本文介紹使用使用WriteXml,ReadXml對DataTable序列化還原序列化,同時處理"DataTable 不支援來自 XML 的架構推斷。"錯誤.

由於DataTable本身就實現了ISerializable, IXmlSerializable介面.所以本身就支援序列化還原序列化.

DataTable是個很好的資料類型

1.資料庫中的表完全對應.

2.Repleater,DataGrid等控制項都支援對它的綁定.

3.在代碼中迴圈遍曆特別方便.

但為了網路傳輸,或者離線儲存,就需要序列化還原序列化為xml.WriteXml,ReadXml就是實現次目的的. 

一.使用WriteXml序列化DataTable: 

準備資料: 

  1. create table sitemaps   
  2. (  
  3.     url varchar(255),  
  4.     title varchar(255)  
  5. )  
  6.   
  7. insert sitemaps   
  8. select 'http://www.it118.org', 'it智庫網'  
  9. union all  
  10. select 'http://bbs.it118.org', 'it智庫網論壇'  

C#處理代碼:

  1. SqlConnection connection = new SqlConnection("Server=localhost;Database=testdb;uid=sa;pwd=sa");  
  2.   
  3. connection.Open();  
  4.   
  5. SqlCommand selectCommand = new SqlCommand(string.Format("SELECT * from sitemaps"), connection);  
  6.   
  7. DataTable dataTable = new DataTable("sitemaps");  //注意table一定需要有tablename
  8. new SqlDataAdapter(selectCommand).Fill(dataTable);  
  9.   
  10. connection.Close();  
  11.   
  12. dataTable.WriteXml("d:\\sitemaps.xml");  

其中sitemaps.xml:  

  1. <?xml version="1.0" standalone="yes"?>  
  2. <DocumentElement>  
  3.   <sitemaps>  
  4.     <url>http://www.it118.org</url>  
  5.     <title>it智庫網</title>  
  6.   </sitemaps>  
  7.   <sitemaps>  
  8.     <url>http://bbs.it118.org</url>  
  9.     <title>it智庫網論壇</title>  
  10.   </sitemaps>  
  11. </DocumentElement>  
二.使用ReadXml序列化DataTable:

如果代碼如下: 

  1. DataTable dt = new DataTable();  
  2. dt.ReadXml("d:\\sitemaps.xml");  

就會提示:DataTable 不支援來自 XML 的架構推斷。

正確代碼如下: 

  1. DataTable dt = new DataTable("sitemaps");  
  2. dt.Columns.Add("url");  
  3. dt.Columns.Add("title");  
  4. dt.ReadXml("d:\\sitemaps.xml");  
三.應用

我曾經有特殊需要.在本地使用WriteXml產生xml,傳輸到別的地方使用ReadXml讀取.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.