代碼保存為Asp_XML.ASP運行即可:
<%
’By Dicky 2005-03-22 21:52:18 AM QQ:25941 E-mail:AppleBBS@GMail.Com
Const IsSql = 1 ’定義數據庫類型為SQL Server
Call OpenConn(Conn) ’打開數據庫連接
Dim Rs,Sql
Set Rs = Server.CreateObject("ADODB.RecordSet")
Sql = "SELECT * FROM Products ORDER BY ProductName"
Rs.Open Sql,Conn,1,1 ’以只讀方式查詢數據記錄
If Rs.Eof Then
Response.Write "Sorry,no record!" ’如果沒有記錄
Else
Dim objXMLDOM, objRootNode, objNode
Set objXMLDOM = Server.CreateObject("MSXML2.DOMDocument") ’創建XML文檔對象
Set objRootNode = objXMLDOM.createElement("XML") ’創建根節點
objXMLDOM.documentElement = objRootNode
Do While Not Rs.Eof ’循環出所有記錄
’ Response.Write Rs("ProductName") &"<br>"
Set objRowNode = objXMLDOM.createElement("row") ’創建父節點
Set objNode = objXMLDOM.createElement("ProductName") ’創建子節點
objNode.text = Rs("ProductName")
objRowNode.appendChild(objNode)
Set objNode = objXMLDOM.createElement("UnitPrice")
objNode.text = Rs("UnitPrice")
objRowNode.appendChild(objNode)
Set objNode = objXMLDOM.createElement("UnitsInStock")
objNode.text = Rs("UnitsInStock")
objRowNode.appendChild(objNode)
objRootNode.appendChild(objRowNode)
Rs.MoveNext:Loop ’循環結束
objXMLDOM.Save "D:\MyXMLDoc.xml" ’寫入XML文件 可以用變量讓用戶在頁面上自定義文件名
Response.Write "<script>alert(’恭喜,寫入XML文件成功!’);</script>"
Set objNode = Nothing ’銷毀對象
Set objRowNode = Nothing ’銷毀對象
Set objRootNode = Nothing ’銷毀對象
End If
Rs.Close
Set Rs = Nothing
Call CloseConn() ’關閉數據庫連接
Function OpenConn(Conn) ’打開數據庫連接
Dim ConnStr
If IsSql = 1 Then ’如果是SQL Server數據庫
’SQL Server數據庫連接參數:用戶名、用戶密碼、數據庫名、連接名(本地用local,外地用IP)
Dim SqlUsername,SqlPassWord,SqlDatabaseName,SqlLocalName
SqlUsername = "sa"
SqlPassWord = ""
SqlDatabaseName = "Northwind"
SqlLocalName = "(local)"
ConnStr = "Provider = Sqloledb; User ID = " & SqlUsername & ";
Password = " & SqlPassWord & "; Initial Catalog = " & SqlDatabaseName & ";
Data Source = " & SqlLocalName & ";"
Else ’如果是Access數據庫
Dim Db
’第一次使用請修改本處數據庫地址並相應修改數據庫名稱,如將Dicky.mdb修改為Dicky.ASP(防止惡意下載Access數據庫)
Db = "Dicky.mdb"
ConnStr = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source =
" & Server.MapPath(Db)
End If
On Error Resume Next
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open ConnStr
If Err Then
’ Err.Clear
Set Conn = Nothing
Response.Write "數據庫連接出錯,請檢查連接字串。"
Response.End
End If
Set Rs = Server.CreateObject("Adodb.RecordSet")
End Function
Function CloseConn() ’關閉數據庫連接
Conn.Close
Set Conn = Nothing
End Function
%>