xml和.net是完全融合的,很多.net的服務器控件都具備了一種或更多種創建xml文件的能力,dataset類就包含若干種創建xml文件的方法,在這篇文章中,我們將創建dataset與xml之間的連接的例子,而這個例子的作用就是從數據庫里讀出數據填入dataset對象中,然后再從dataset對象輸出為xml文件保存到磁盤里,當然了 ,我們還可以為xml文件創建與它相關的schema文件。
把dataset保存為xml文件中的asp.net頁面文件(.aspx),簡單的甚至可以用可笑來形容了,實質上,它根本沒有包含一句關鍵性的代碼,我們需要做的僅僅是添加一句提示信息--“完成”,而真正體現功能的代碼是在code-behind的后置代碼文件中,下面是asp.net web頁面(.aspx):
<%@ page language="vb" src="datasettoxml.aspx.vb" inherits="datasettoxml" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>datasettoxml</title>
<meta name="generator" content="microsoft visual studio.net 7.0">
<meta name="code_language" content="visual basic 7.0">
<meta name=vs_defaultclientscript content="javascript">
<meta name=vs_targetschema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body ms_positioning="gridlayout">
<form id="form1" method="post" runat="server">
</form>
<h3>done!</h3>
</body>
</html>
實際上,code-behind后置文件也不是很復雜,它的大多數代碼都是我們很熟悉的了,如使用dataadapter對象來填充dataset對象,為了使xml不會變的很大,我們把從northwind數據的customers表中查詢數據的sql的select語句加上了top 10,真正有作用的代碼只有兩行,一行用來把dataset輸出為xml文件,另一行創建它的schema文件,在文章我把它標記為紅色,在這個例子中,我們使用了dataset類的兩個方法:writexml和writexmlschema,而server.mappath則是用來把兩個文件寫到web應用程序中的根目錄下,這個兩個文件將分別叫做“customers.xml“和”custmers.xsd“,代碼如下:
imports system
imports system.data
imports system.data.sqlclient
imports system.configuration public class datasettoxml : inherits system.web.ui.page
private sub page_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
dim objconn as sqlconnection
dim strsql as string
strsql = "select top 10 * from customers"
objconn = new sqlconnection(configurationsettings.appsettings("connectionstring"))
dim sdacust as new sqldataadapter(strsql, objconn)
dim dstcust as new dataset()
sdacust.fill(dstcust, "customers")
'save data to xml file and schema file
dstcust.writexml(server.mappath("customers.xml"),xmlwritemode.ignoreschema)
dstcust.writexmlschema(server.mappath("customers.xsd"))
end sub
end class
到此我為寫了一篇那么簡單的文章而深感歉意,但實際上,真正應該感到抱歉的應該是微軟的.net,是它讓我們從數據表把數據轉換為xml文件變的如此簡單,我希望你能相信這一點!
菜鳥學堂: