递归生成树
为了让大家看清问题的本质,我首先放出一个简单的递归,只完成基本功能:
01.private void ResolveMenuTree2(JSONArray ja, List<string> treePathList, bool showAllErrors, ExtAspNet.TreeNodeCollection nodes)
02.{
03. for (int i = 0; i < ja.Count; i++)
04. {
05. JSONObject kid = ja[i] as JSONObject;
06. string name = kid.getString("name");
07. // 当前路径,如果basePath存在说明是根目录
08. if (kid.has("basePath"))
09. {
10. treePathList.Add(kid.getString("basePath"));
11. }
12. else
13. {
14. treePathList.Add (name);
15. }
16. string currentPath = GetTreePath (treePathList);
17.
18. string type = kid.getString ("type");
19. // 如果文件夹中没有文件,则不添加此文件夹
20. if (type == "folder" && kid.getInt("fileCount") == 0)
21. {
22. treePathList.RemoveAt(treePathList.Count - 1);
23. continue;
24. }
25. ExtAspNet.TreeNode node = new ExtAspNet.TreeNode();
26. nodes.Add (node);
27. node.Text = name;
28. node.Text = String.Format("<span qtip=\"{0}\">{1}</span>", currentPath, node.Text);
29. if (type == "folder")
30. {
31. node.SingleClickExpand = true;
32. ResolveMenuTree2(kid.getJSONArray("kids"), treePathList, showAllErrors, node.Nodes);
33. }
34. else
35. {
36. node.Leaf = true;
37. }
38. treePathList.RemoveAt(treePathList.Count - 1);
39. }
40.}
在这段代码中,我们通过treePathList来记录当前节点的路径,这也是一个关键点。
此时生成的页面截图: