开发学院

您的位置:首页>教程>正文

教程正文

ASP .NET - XML 文件

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>


    把 DataSet 绑定到 List 控件

    首先,导入 "System.Data" 命名空间。我们需要该命名空间与 DataSet 对象一起工作。把下面这条指令包含在 .htmlx 页面的顶部:

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

    接下来,为这个 XML 文件创建一个 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 控件,首先请在 .htmlx 页面中创建一个 RadioButtonList 控件(没有任何 asp:ListItem 元素):

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

    然后添加构建这个 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 控件中的项目时执行。当用户点击某个单选按钮时,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 subsub 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>