萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 輸出 XML 數據:ADO Recordset 持久化為 XML 的兩種模式 (IIS 4.0/5.0)

ASP 返回 XML 是 Web Service、AJAX 後端、數據交換的基礎。IIS 版本差異導致實現方式不同:IIS 5.0 (ASP 3.0) 支援直接流式輸出,IIS 4.0 需中轉 DOMDocument。

核心原則:Content-Type 必須優先設定

<%
' 第一行必須設定,否則瀏覽器按 HTML 渲染顯示空白
Response.ContentType = "text/xml"
%>

方案一:IIS 5.0 / ASP 3.0 (Windows 2000+) - 直接流式輸出

<%
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
%>

方案二:IIS 4.0 / ASP 2.0 (Windows NT 4.0) - 中轉 DOMDocument

<%
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
%>

關鍵差異對比

| 特性 | IIS 5.0 (ASP 3.0) | IIS 4.0 (ASP 2.0) | |------|-------------------|-------------------| | Response 介面 | 實作 IStream | 僅支援 Write 字符串 | | 輸出方式 | rs.Save Response, 1 直接流式 | rs.Save xmlDoc, 1 → Response.Write xmlDoc.xml | | 記憶體佔用 | 低 (流式) | 高 (完整 XML 在記憶體) | | 代碼複雜度 | 簡單 | 需額外 DOMDocument |

輸出 XML 結構範例

<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"
  • ❌ 大數據量記憶體溢出 (IIS 4.0) → 分頁查詢、或升級 IIS 5.0+ 使用流式輸出
  • ❌ CursorLocation 錯誤 → 必須設 adUseClient (3),伺服端游標不支援 XML 持久化

現代化建議

ASP 時代方案已退役。新專案請使用:

  • ASP.NET Core:return Ok(data) 自動序列化 JSON/XML
  • Web API / WCF / gRPC:契約優先、強類型、高效能
  • ADO.NET + XmlSerializer:完全控制輸出格式

理解歷史演進,才能在維護舊系統時遊刃有餘。

copyright © 萬盛學電腦網 all rights reserved