以下示範如何在 ASP 中動態產生 XML,重點在於兩個自訂函式:一個負責轉義特殊字元,另一個負責把資料庫的紀錄集轉成 XML 字串。
由於 XML 對 &、<、>、引號等字元有語法要求,寫入前必須先轉義,避免破壞文件結構:
Function ReplaceChar ( FstrSource ) dim strRet if IsNull(FstrSource) then FstrSource = "" strRet = Replace ( FstrSource , "&" , "&" ) strRet = Replace ( strRet , "<" , "<" ) strRet = Replace ( strRet , ">" , ">" ) strRet = Replace ( strRet , """" , """ ) strRet = Replace ( strRet , "'" , "'" ) ReplaceChar = strRet End Function
接著用 RstToXML 函式,把傳入的 Recordset 逐筆轉成 <Record> 節點,並以屬性承載各欄位值:
function RstToXML (FrstRst, FstrRstName) dim strSpace, intLevel, strXML intLevel = 0 strSpace = space(intLevel * 2) if Len(FstrRstName)>0 then strXML = strSpace & "<" & FstrRstName & ">" & vbCR intLevel = intLevel + 1 strSpace = space(intLevel*2) end if if FrstRst.EOF then strXML = strXML & strSpace & "<Record/>" & vbCR RstToXML = strXML exit function end if intLevel = intLevel + 1 strSpace = space(intLevel * 2) dim strTemp FrstRst.MoveFirst do while not FrstRst.EOF strTemp = "" for each objField in FrstRst.FIElds strTemp = strTemp & space(1) & objFIEld.Name & "=" & _ """" & ReplaceChar(objFIEld.Value) & """" next strXML = strXML & "<Record " & strTemp & "/>" & vbCR FrstRst.MoveNext loop intLevel = intLevel - 1 strSpace = space(intLevel * 2) if Len(FstrRstName)>0 then strXML = strXML & strSpace & "</" & FstrRstName & ">" & vbCR end if RstToXML = strXML end function
在頁面中,一邊遍歷系所資料,一邊把統計結果寫成屬性,最後由伺服器組裝成 XML:
<?XML version="1.0" encoding="gb2312"?>
<root>
<%
set conn = server.CreateObject("ADODB.Connection")
conn.Open "FILEDSN=test.dsn"
set facultyRst = conn.Execute("select * from faculty")
do while not facultyRst.eof
strFaculty = facultyRst("name")
set classRst = conn.Execute("select count(id) as classcount from recruitclass where recruityear=" & cstr(year(now)) & " and faculty='" & strFaculty & "'")
set maleRst = conn.Execute("select count(id) as malecount from newstudent where recruityear=" & cstr(year(now)) & " and faculty='" & strFaculty & "' and gender='男'")
set femaleRst = conn.Execute("select count(id) as femalecount from newstudent where recruityear=" & cstr(year(now)) & " and faculty='" & strFaculty & "' and gender='女'")
%>
<newstudent faculty="<%=strFaculty%>" class="<%=classRst("classcount")%>" male="<%=maleRst("malecount")%>" female="<%=femaleRst("femalecount")%>"/>
<%
facultyRst.MoveNext
loop
%>
</root>
若不你想手動組字串,也可以直接讓 Recordset 存檔為 XML:
<%
dim strConn, strSQL, rs, sFileName
strConn = "Provider=SQLOLEDB;Server=localhost;Database=pubs;UID=sa;PWD=;"
strSQL = "SELECT * FROM employee"
set rs = Server.CreateObject("ADODB.Recordset")
rs.open strSQL, strConn, 1, 1
sFileName = "c:\temp\employee.XML"
rs.save sFileName, 1
rs.close
set rs = nothing
%>
若想直接把 XML 輸出到瀏覽器,只要把 ContentType 設為 text/XML,並用 rs.save Response, 1 即可。