xml和.net是完全融合的,很多.net的服務(wù)器控件都具備了一種或更多種創(chuàng)建xml文件的能力,dataset類就包含若干種創(chuàng)建xml文件的方法,在這篇文章中,我們將創(chuàng)建dataset與xml之間的連接的例子,而這個(gè)例子的作用就是從數(shù)據(jù)庫里讀出數(shù)據(jù)填入dataset對(duì)象中,然后再從dataset對(duì)象輸出為xml文件保存到磁盤里,當(dāng)然了 ,我們還可以為xml文件創(chuàng)建與它相關(guān)的schema文件。
把dataset保存為xml文件中的asp.net頁面文件(.aspx),簡(jiǎn)單的甚至可以用可笑來形容了,實(shí)質(zhì)上,它根本沒有包含一句關(guān)鍵性的代碼,我們需要做的僅僅是添加一句提示信息--“完成”,而真正體現(xiàn)功能的代碼是在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>
實(shí)際上,code-behind后置文件也不是很復(fù)雜,它的大多數(shù)代碼都是我們很熟悉的了,如使用dataadapter對(duì)象來填充dataset對(duì)象,為了使xml不會(huì)變的很大,我們把從northwind數(shù)據(jù)的customers表中查詢數(shù)據(jù)的sql的select語句加上了top 10,真正有作用的代碼只有兩行,一行用來把dataset輸出為xml文件,另一行創(chuàng)建它的schema文件,在文章我把它標(biāo)記為紅色,在這個(gè)例子中,我們使用了dataset類的兩個(gè)方法:writexml和writexmlschema,而server.mappath則是用來把兩個(gè)文件寫到web應(yīng)用程序中的根目錄下,這個(gè)兩個(gè)文件將分別叫做“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
到此我為寫了一篇那么簡(jiǎn)單的文章而深感歉意,但實(shí)際上,真正應(yīng)該感到抱歉的應(yīng)該是微軟的.net,是它讓我們從數(shù)據(jù)表把數(shù)據(jù)轉(zhuǎn)換為xml文件變的如此簡(jiǎn)單,我希望你能相信這一點(diǎn)!
菜鳥學(xué)堂: