<?xml version="1.0" encoding="utf-8" ?>
<backup>
<item num="1" time ="2009-02-24 0:00:00"></item>
<item num="2" time="2009-02-25 12:00:00"></item>
</backup>
----------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dt = new DataTable(); DataColumn dc = new DataColumn("num"); dt.Columns.Add(dc); dc = new DataColumn("time"); dt.Columns.Add(dc); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Server.MapPath("~/XMLFile.xml")); //xml文件的路径 XmlNodeList xnl = xmlDoc.SelectSingleNode("backup").ChildNodes; for (int i = 0; i < xnl.Count; i++) { string num = xnl.Item(i).Attributes["num"].Value; string time = xnl.Item(i).Attributes["time"].Value; DataRow dr = dt.NewRow(); dr[0] = num; dr[1] = time; dt.Rows.Add(dr); } for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; ListBox1.Items.Add(new ListItem(dr["time"].ToString(), dr["num"].ToString())); } } }
如果用Linq更简单:
//引用using System.Xml.Linq; XDocument doc = XDocument.Load(Server.MapPath("~/XMLFile.xml")); var list = from p in doc.Descendants("item") select new { num = (int)p.Attribute("num"), time = (DateTime)p.Attribute("time") }; foreach (var v in list) { ListBox1.Items.Add(new ListItem(v.time.ToString(), v.num.ToString())); }