ASP .NET - XML 文件
我們可以把 XML 文件綁定到列表控件。
一個 XML 文件
這里有一個名為 "countries.xml" 的 XML 文件:
<?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country> <text>China</text> <value>C</value> </country> <country> <text>Sweden</text> <value>S</value> </country> <country> <text>France</text> <value>F</value> </country> <country> <text>Italy</text> <value>I</value> </country> </countries>
請查看該文件:countries.xml
把 DataSet 綁定到 List 控件
首先,導入 "System.Data" 命名空間。我們需要該命名空間與 DataSet 對象一起工作。把下面這條指令包含在 .aspx 頁面的頂部:
<%@ Import Namespace="System.Data" %>
接下來,為這個 XML 文件創(chuàng)建一個 DataSet,并在頁面首先加載時把這個 XML 文件載入該 DataSet:
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub
如需把該 DataSet 綁定到 RadioButtonList 控件,首先請在 .aspx 頁面中創(chuàng)建一個 RadioButtonList 控件(沒有任何 asp:ListItem 元素):
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>
然后添加構(gòu)建這個 XML DataSet 的腳本:
<%@ Import Namespace="System.Data" %> <script runat="server"> sub Page_Load if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind() end if end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> </form> </body> </html>
然后,我們添加一個子例程,該子例程會在用戶點擊 RadioButtonList 控件中的項目時執(zhí)行。當用戶點擊某個單選按鈕時,label 中會出現(xiàn)一條文本:
<%@ Import Namespace="System.Data" %>
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New DataSet
mycountries.ReadXml(MapPath("countries.xml"))
rb.DataSource=mycountries
rb.DataValueField="value"
rb.DataTextField="text"
rb.DataBind()
end if
end sub
sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>
</body>
</html>