我在开发系统,特别是管理系统的时候,经常需要用到TreeView来作为导航的载体。现在将把XML文件绑定到TreeView的方法贴出,供大家指点。
以下是XML代码:
1<?xml version="1.0" encoding="utf-8" ?>
2<ContentPage>
3 <MenuTitle id="1" value="用户管理实例一">
4 <ContentPageRecord>
5 <ContentCode>11</ContentCode>
6 <ContentTitle>新增新闻</ContentTitle>
7 <ContentPath>URL</ContentPath>
8 </ContentPageRecord>
9 <ContentPageRecord>
10 <ContentCode>12</ContentCode>
11 <ContentTitle>更新新闻</ContentTitle>
12 <ContentPath>URL</ContentPath>
13 </ContentPageRecord>
14 <ContentPageRecord>
15 <ContentCode>13</ContentCode>
16 <ContentTitle>删除新闻</ContentTitle>
17 <ContentPath>URL</ContentPath>
18 </ContentPageRecord>
19 </MenuTitle>
20
21 <MenuTitle id="2" value="用户管理实例二">
22 <ContentPageRecord>
23 <ContentCode>21</ContentCode>
24 <ContentTitle>新增用户</ContentTitle>
25 <ContentPath>URL</ContentPath>
26 </ContentPageRecord>
27 <ContentPageRecord>
28 <ContentCode>22</ContentCode>
29 <ContentTitle>更新用户</ContentTitle>
30 <ContentPath>URL</ContentPath>
31 </ContentPageRecord>
32 <ContentPageRecord>
33 <ContentCode>23</ContentCode>
34 <ContentTitle>删除用户</ContentTitle>
35 <ContentPath>URL</ContentPath>
36 </ContentPageRecord>
37
38 </MenuTitle>
39</ContentPage>
40
下面则是绑定方法:
1 protected void DataBindTreeView()
2 {
3 DataSet ds = new DataSet();
4 ds.ReadXml(Server.MapPath(@"MoviesList.xml"));
5 if (ds != null)
6 {
7 foreach (DataRow function in ds.Tables[0].Rows)
8 {
9 if (string.IsNullOrEmpty(function["Value"].ToString())) continue;
10 TreeNode Root = new TreeNode();
11 Root.Text = function["Value"].ToString();
12 Root.Value = function["id"].ToString();
13 Root.Expanded = false;
14
15 DataRow[] childrows = ds.Tables[1].Select("MenuTitle_Id=" + function["MenuTitle_Id"]);
16 if (childrows.Length > 0)
17 {
18 foreach (DataRow chRow in childrows)
19 {
20 if (string.IsNullOrEmpty(chRow["ContentTitle"].ToString())) continue;
21 string selectedNode = Session["System_Selected_Node"] as string;
22 if (selectedNode == chRow["ContentTitle"].ToString())
23 Root.Expanded = true;
24
25 TreeNode temp = new TreeNode();
26 temp.Text = chRow["ContentTitle"].ToString();
27 temp.Value = chRow["ContentCode"].ToString();
28 temp.NavigateUrl = chRow["ContentPath"].ToString();
29 Root.ChildNodes.Add(temp);
30 }
31 }
32 TreeView1.Nodes.Add(Root);
33 }
34 }
35 }
以上仅供参考。 多谢指点!