读取XML并绑定至RadioButtonList

读取XML的文档,可以使用System.Data.DataSet类别中的ReadXml()方法。如下面的xml文档,放在站点的根目录之下:

YearOfBirth.xml
xml version="1.0" encoding="utf-8" ?>
<YearOfBirths>
  <YearOfBirth>
    <ID>1ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>2ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>3ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>4ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>5ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>6ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>7ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>8ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>9ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>10ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>11ID>
    <Name>Name>
  YearOfBirth>
  <YearOfBirth>
    <ID>12ID>
    <Name>Name>
  YearOfBirth>
YearOfBirths>


使用一个属性来获取这个文档:

 private string XmlFile
    {
        get
        {
            return Server.MapPath("~/YearOfBirth.xml");
        }
    }


在aspx网页上拉一个RadioButtonList控件,用来显示XML的数据。

<asp:RadioButtonList ID="RadioButtonListYearOfBirth" runat="server" RepeatColumns="6" RepeatDirection="Horizontal">asp:RadioButtonList>


接下来,用DataSet去读取刚才写好的获取XML文件的属性。

View Code
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Data_Binding();

    }

    private void Data_Binding()
    {
        using (DataSet ds = new DataSet())
        {
            ds.ReadXml(XmlFile);
            this.RadioButtonListYearOfBirth.DataSource = ds;
            this.RadioButtonListYearOfBirth.DataTextField = "Name";
            this.RadioButtonListYearOfBirth.DataValueField = "ID";
            this.RadioButtonListYearOfBirth.DataBind();
        }
    }
}


网页运行效果:

读取XML并绑定至RadioButtonList_第1张图片

 

你可能感兴趣的:(读取XML并绑定至RadioButtonList)