在写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));
}
}
---------------------------------------龙亿-----原创---------------------------------------------------------