ASP 返回 XML 是 Web Service、AJAX 後端、數據交換的基礎。IIS 版本差異導致實現方式不同:IIS 5.0 (ASP 3.0) 支援直接流式輸出,IIS 4.0 需中轉 DOMDocument。
<%
' 第一行必須設定,否則瀏覽器按 HTML 渲染顯示空白
Response.ContentType = "text/xml"
%>
<%
Response.ContentType = "text/xml"
Dim cn, rs
Set cn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
' 修改為你的連接字串
cn.Open "Provider=SQLOLEDB.1;Data Source=.;Initial Catalog=pubs;User ID=sa;Password=;"
rs.CursorLocation = 3 ' adUseClient (必須!才能持久化為 XML)
rs.Open "SELECT * FROM Authors", cn
' 核心:直接持久化到 Response 物件 (實現 IStream)
' adPersistXML = 1
rs.Save Response, 1
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
%>
<%
Response.ContentType = "text/xml"
Dim cn, rs, xmlDoc
Set cn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
cn.Open "Provider=SQLOLEDB.1;Data Source=.;Initial Catalog=pubs;User ID=sa;Password=;"
rs.CursorLocation = 3
rs.Open "SELECT * FROM Authors", cn
' 必須先存到 DOMDocument,再輸出 XML 字符串
Set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")
rs.Save xmlDoc, 1 ' adPersistXML
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
' 輸出完整 XML 字符串
Response.Write xmlDoc.xml
Set xmlDoc = Nothing
%>
IStream | 僅支援 Write 字符串 |
| 輸出方式 | rs.Save Response, 1 直接流式 | rs.Save xmlDoc, 1 → Response.Write xmlDoc.xml |
| 記憶體佔用 | 低 (流式) | 高 (完整 XML 在記憶體) |
| 代碼複雜度 | 簡單 | 需額外 DOMDocument |
<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<elementtype name="row" content="eltOnly" rs:CommandTimeout="30">
<attribute type="au_id" rs:number="1" rs:write="true"/>
<attribute type="au_lname" rs:number="2" rs:write="true"/>
<attribute type="au_fname" rs:number="3" rs:write="true"/>
...
</elementtype>
</s:Schema>
<rs:data>
<row au_id="172-32-1176" au_lname="White" au_fname="Johnson" .../>
<row au_id="213-46-8915" au_lname="Green" au_fname="Marjorie" .../>
</rs:data>
</xml>
Response.ContentType = "text/xml" 是否在第一行、是否有輸出前空白字符Codepage=65001 或儲存過程指定 N'中文',並 Response.CharSet = "utf-8"adUseClient (3),伺服端游標不支援 XML 持久化ASP 時代方案已退役。新專案請使用:
return Ok(data) 自動序列化 JSON/XML理解歷史演進,才能在維護舊系統時遊刃有餘。