很多人以為用 XML 就一定要在客戶端裝解析元件,其實完全不必。XML 只是一份文字檔,伺服器端能不能產生它,跟有沒有安裝 XML 軟體一點關係都沒有。
XML 檔的存放方式與 HTML 檔完全一樣。開記事本,寫入:
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <from>Jani</from> <to>Tove</to> <message>Remember me this weekend</message> </note>
存成 note.xml,放到伺服網站上即可透過 URL 存取。
要在伺服器端產生 XML 回應,只要把內容輸出成文字,關鍵是 ContentType 必須設為 text/xml:
<%
response.ContentType = "text/xml"
response.Write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.Write("<note>")
response.Write("<from>Jani</from>")
response.Write("<to>Tove</to>")
response.Write("<message>Remember me this weekend</message>")
response.Write("</note>")
%>
把這段存成 .asp 檔,瀏覽器或下游程式拜訪該網址時,收到的就是一份 XML。這種寫法的好处是內容可以完全動態——依請求參數、時間或使用者身分產生不同的 XML。
同樣不需要安裝任何 XML 軟體,只要把查詢結果逐列輸出成元素:
<%
response.ContentType = "text/xml"
set conn = Server.CreateObject("ADODB.Connection")
conn.provider = "Microsoft.Jet.OLEDB.4.0"
conn.open server.mappath("/db/database.mdb")
sql = "select fname, lname from tblGuestBook"
set rs = conn.Execute(sql)
response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<guestbook>")
do while not rs.EOF
response.write("<guest>")
response.write("<fname>" & rs("fname") & "</fname>")
response.write("<lname>" & rs("lname") & "</lname>")
response.write("</guest>")
rs.MoveNext()
loop
response.write("</guestbook>")
rs.close()
conn.close()
%>
編碼要對齊。宣告寫 ISO-8859-1 就必須真的輸出該編碼的位元組。若資料庫裡是中文,宣告卻寫 ISO-8859-1,下游解析器會把位元組解讀錯誤而出現亂碼;這時應改成 encoding="UTF-8" 並確保輸出流也是 UTF-8。
特殊字元要轉義。直接將資料庫欄位字串拼接進 XML 是有風險的:內容一旦含 &、<、>,就會破壞文件結構;若資料來自使用者輸入,甚至可能造成 XML 注入。正確做法是用 XML DOM 建立節點並設定文字內容(DOM 會自動處理轉義),或至少自行把 & 替換為 & 再處理其他字元。示範程式中為求簡潔直接串接,正式環境請改用前者。