通常,我們在數據庫中存儲數據。不過,如果希望數據的可移植性更強,我們可以把數據存儲 XML 文件中。
如果數據要被傳送到非 Windows 平臺上的應用程序,那么把數據保存在 XML 文件中是有好處的。請記住,XML 有很強的跨平臺可移植性,并且數據無需轉換!
首先,我們將學習如何創建并保存一個 XML 文件。下面的這個 XML 文件將被命名為 "test.xml",并被保存在服務器上的 c 目錄中。我們將使用 ASP 和微軟的 XMLDOM 對象來創建并保存這個 XML 文件:
<%Dim xmlDoc, rootEl, child1, child2, p'創建XML文檔Set xmlDoc = Server.CreateObject("Microsoft.XMLDOM")'創建根元素并將之加入文檔Set rootEl = xmlDoc.createElement("root")xmlDoc.appendChild rootEl'創建并加入子元素Set child1 = xmlDoc.createElement("child1")Set child2 = xmlDoc.createElement("child2")rootEl.appendChild child1rootEl.appendChild child2'創建 XML processing instruction'并把它加到根元素之前Set p=xmlDoc.createProcessingInstruction("xml","version='1.0'")xmlDoc.insertBefore p,xmlDoc.childNodes(0)'把文件保存到 C 目錄xmlDoc.Save "c:/test.xml"%>
如果您打開這個被保存的文件,它會使這個樣子 ("test.xml"):
<?xml version="1.0"?>
現在,我們看一個真實的表單例子。
我們首先看一下這個被用在例子中的 html 表單:下面的HTML表單要求用戶輸入他們的名字、國籍以及電子郵件地址。隨后這些信息會被寫到一個 XML 文件,以便存儲。
用于以上 HTML 表單的 action 被設置為 "saveForm.asp"。"saveForm.asp" 文件是一個 ASP 頁面,可循環遍表單域,并把它們的值存儲在一個 XML 文件中:
<%dim xmlDocdim rootEl,fieldName,fieldValue,attIDdim p,i'如果有錯誤發生,不允許程序終止On Error Resume NextSet xmlDoc = server.CreateObject("Microsoft.XMLDOM")xmlDoc.preserveWhiteSpace=true'創建并向文檔添加根元素Set rootEl = xmlDoc.createElement("customer")xmlDoc.appendChild rootEl'循環遍歷 Form 集for i = 1 To Request.Form.Count '除去表單中的 button 元素 if instr(1,Request.Form.Key(i),"btn_")=0 then '創建 field 和 value 元素,以及 id 屬性 Set fieldName = xmlDoc.createElement("field") Set fieldValue = xmlDoc.createElement("value") Set attID = xmlDoc.createAttribute("id") '把當前表單域的名稱設置為 id 屬性的值 attID.Text = Request.Form.Key(i) '把 id 屬性添加到 field 元素 fieldName.setAttributeNode attID '把當前表單域的值設置為 value 元素的值 fieldValue.Text = Request.Form(i) '將 field 元素作為根元素的子元素進行添加 rootEl.appendChild fieldName '將 value 元素作為 field 元素的子元素進行添加 fieldName.appendChild fieldValue end ifnext'添加 XML processing instruction'并把它加到根元素之前Set p = xmlDoc.createProcessingInstruction("xml","version='1.0'")xmlDoc.insertBefore p,xmlDoc.childNodes(0)'保存 XML 文件xmlDoc.save "c:/Customer.xml"'釋放所有的對象引用set xmlDoc=nothingset rootEl=nothingset fieldName=nothingset fieldValue=nothingset attID=nothingset p=nothing'測試是否有錯誤發生if err.number<>0 then response.write("Error: No information saved.")else response.write("Your information has been saved.")end if%>
注釋:如果指定的 XML 文件名已經存在,那個文件會被覆蓋!
XML 文件會由上面的代碼生成,大致的樣子是這樣的:("Customer.xml"):
<?xml version="1.0" ?>David Smith China [email protected]
新聞熱點
疑難解答