利用ASP.NET的ExecuteXmlReader將資料庫的資料轉成xml格式
最近看到一篇文章介紹ExecuteXmlReader的用法...
如何透過ExecuteXmlReader將資料庫的資料轉成xml格式...
小弟寫了一個範例..分享給大家呀....
asp.net(c#)範例
ExecuteXmlReader.aspx
01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExecuteXmlReader.aspx.cs"
02 Inherits="ExecuteXmlReader" %>
03
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07 <title>ExecuteXmlReader</title>
08 </head>
09 <body>
10 <form id="form1" runat="server">
11 <div>
12 </div>
13 </form>
14 </body>
15 </html>
16
02 Inherits="ExecuteXmlReader" %>
03
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07 <title>ExecuteXmlReader</title>
08 </head>
09 <body>
10 <form id="form1" runat="server">
11 <div>
12 </div>
13 </form>
14 </body>
15 </html>
16
ExecuteXmlReader.aspx.cs
01
using System;
02
using System.Data;
03
using System.Configuration;
04
using System.Collections;
05
using System.Web;
06
using System.Web.Security;
07
using System.Web.UI;
08
using System.Web.UI.WebControls;
09
using System.Web.UI.WebControls.WebParts;
10
using System.Web.UI.HtmlControls;
11
using System.Xml;
12
using System.Data.SqlClient;
13
14
public partial class ExecuteXmlReader : System.Web.UI.Page
15
{
16
protected void Page_Load(object sender, EventArgs e)
17
{
18
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString))
19
{
20
XmlDocument xml = new XmlDocument();
21
connection.Open();
22
//xml格式1,請看執行結果1
23
string queryString = "SELECT id,gender FROM [user] FOR XML AUTO,root('root')";
24
//xml格式2,請看執行結果2
25
//string queryString = "SELECT id,gender FROM [user] FOR XML AUTO,root('root'),elements";
26
SqlCommand command = new SqlCommand(queryString, connection);
27
xml.Load(command.ExecuteXmlReader());
28
xml.Save(Server.MapPath("user.xml"));
29
}
30
}
31
32
}

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

執行結果1:
執行結果2:
參考來源:
巢狀 FOR XML 查詢
SqlCommand ExecuteXmlReader Method