1 //連接配接資料庫
2 SqlConnection con = new SqlConnection("server=****;database=****;uid=sa;pwd=********");
3
4 /// <summary>
5 /// 提取資料表儲存為XML檔案
6 /// </summary>
7 /// <param name="sender"></param>
8 /// <param name="e"></param>
9 private void button3_Click(object sender, EventArgs e)
10 {
11 try
12 {
13 //打開資料庫
14 con.Open();
15
16 //當資料庫為打開時
17 if (con.State == ConnectionState.Open)
18 {
19
20 //聲明一個DataTable 存儲資料
21 DataTable dt = new DataTable();
22 //SQL語句
23 string str = "select * from CurrentStock";
24
25 //聲明一個sql資料擴充卡執行sql語句
26 SqlDataAdapter sad = new SqlDataAdapter(str, con);
27
28 //将SQLql資料擴充卡的内容填充到DATATABEL
29 sad.Fill(dt);
30
31 //當DataTable的内容大于0 時,向下執行
32 if (dt.Rows.Count > 0)
33 {
34
35 //建立一個DOM對象
36 XDocument xDoc = new XDocument();
37 //建立XML文檔的聲明語句
38 XDeclaration xDec = new XDeclaration("1.0", "UTF-8", "no");
39 //将聲明語句給XML文檔xDoc
40 xDoc.Declaration=xDec;
41
42 //建立一個根節點
43 XElement xrootElement = new XElement("CurrentStock");
44 //将根節點添加到XML文檔xDoc中
45 xDoc.Add(xrootElement);
46
47 //周遊DataTable的每一行
48 for (int i = 0; i < dt.Rows.Count; i++)
49 {
50 //建立一個子節點,區分每一行的資料
51 XElement xElementRow = new XElement("Row");
52 //給子節點Row添加一屬性,這裡是行号,識别一共有多少行
53 xElementRow.SetAttributeValue("Autoid", (i + 1).ToString());
54
55 //周遊每一列,主要擷取列名
56 for (int j = 0; j <dt.Columns.Count; j++)
57 {
58 //向子節點Row中添加子元素, 元素的名稱是dt中的清單 ,值是dt中每一行每一列的值
59 xElementRow.SetElementValue(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString().Trim());
60
61 }
62
63 //将子點節Row添加到根節點下
64 xrootElement.Add(xElementRow);
65
66
67
68 }
69
70 //儲存XML檔案
71 xDoc.Save("TableNameA");
72
73 //提示成功
74 MessageBox.Show("OK");
75
76 }
77
78 else
79 {
80
81 MessageBox.Show("表中沒有資料!");
82
83 }
84
85
86 }
87 else
88 {
89 MessageBox.Show("資料庫連接配接出錯,請檢查!");
90
91 }
92
93
94 }
95 catch
96 {
97
98
99 throw;
100
101 }
102
103
104 con.Close();
105 }