ASP.NET - Tệp XML

Chúng ta có thể gán tệp XML vào điều khiển danh sách.

Một tệp XML

Có một tệp XML có tên là "countries.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>

Vui lòng xem tệp này:countries.xml

Gán DataSet vào điều khiển List

Đầu tiên, nhập tên không gian tên "System.Data" .Chúng ta cần không gian tên này để làm việc với đối tượng DataSet. Đặt câu lệnh sau vào phần trên của tệp .aspx:

<%@ Import Namespace="System.Data" %>

Tiếp theo, tạo một DataSet cho tệp XML này và tải tệp XML vào DataSet khi trang được tải đầu tiên:

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub

Nếu cần gán DataSet này vào điều khiển RadioButtonList, trước tiên hãy tạo một điều khiển RadioButtonList trong tệp .aspx (không có phần tử asp:ListItem):

<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>
</body>
</html>

Sau đó thêm đoạn mã để xây dựng XML DataSet này:

<%@ 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>

Sau đó, chúng ta thêm một hàm con, hàm con này sẽ được thực thi khi người dùng nhấp vào mục của RadioButtonList. Khi người dùng nhấp vào một radio button, một đoạn văn bản sẽ xuất hiện trong label:

<%@ 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>

Hiển thị ví dụ này