在写Windows环境下,常会用到Tree控件,以下是通过XML文件构建Tree控件树形的方法.
添加一个引用
using System.XML.Linq;
Code
public static void LoadTree(TreeView tv)
{
tv.Nodes.Clear();
XDocument doc = XDocument.Load(SaveData.xmlPath);
IEnumerable<XElement> q = from p in doc.Element("nodeList").Elements("node")
select p;
foreach (var n in q)
{
TreeNode node=new TreeNode();
string name=n.Attribute("name").Value;
node.Text =name;
tv.Nodes.Add(node);
childTree(node, q.Where(c => c.Attribute("name").Value == name));
}
}
private static void childTree(TreeNode node, IEnumerable<XElement> x)
{
var q = from p in x.Elements("childNode")
select p;
foreach (var n in q)
{
TreeNode tn = new TreeNode();
string name = n.Attribute("name").Value;
tn.Text = name;
node.Nodes.Add(tn);
childTree(tn, q.Where(c => c.Attribute("name").Value == name));
}
}
public static void LoadTree(TreeView tv)
{
tv.Nodes.Clear();
XDocument doc = XDocument.Load(SaveData.xmlPath);
IEnumerable<XElement> q = from p in doc.Element("nodeList").Elements("node")
select p;
foreach (var n in q)
{
TreeNode node=new TreeNode();
string name=n.Attribute("name").Value;
node.Text =name;
tv.Nodes.Add(node);
childTree(node, q.Where(c => c.Attribute("name").Value == name));
}
}
private static void childTree(TreeNode node, IEnumerable<XElement> x)
{
var q = from p in x.Elements("childNode")
select p;
foreach (var n in q)
{
TreeNode tn = new TreeNode();
string name = n.Attribute("name").Value;
tn.Text = name;
node.Nodes.Add(tn);
childTree(tn, q.Where(c => c.Attribute("name").Value == name));
}
}
---------------------------------------龙亿-----原创---------------------------------------------------------
作者:龙亿
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。