C# 我想根据xml文件创建treeview(父、子、孙等等)
我有xml文件,有200个节点,如下所示:C# 我想根据xml文件创建treeview(父、子、孙等等),c#,xml,C#,Xml,我有xml文件,有200个节点,如下所示: <grand name="AAA" id="1" father="0"></grand> <grand name="BBB" id="2" father="1"></grand> <grand name="CCC" id="3" father="1"></grand> <grand name="DDD"
<grand name="AAA" id="1" father="0"></grand>
<grand name="BBB" id="2" father="1"></grand>
<grand name="CCC" id="3" father="1"></grand>
<grand name="DDD" id="4" father="2"></grand>
<grand name="EEE" id="5" father="2"></grand>
<grand name="FFF" id="6" father="5"></grand>
<grand name="GGG" id="7" father="5"></grand>
<grand name="HHH" id="8" father="5"></grand>
<grand name="III" id="9" father="6"></grand>
<grand name="JJJ" id="10" father="7"></grand>
感谢大家看起来您意外地生成了另一个AddAllChildren方法。 尝试删除它 TreeNode构造函数新的TreeNode(str.Id);创建Text=str.Id的节点 稍后,您将使用以下内容覆盖它:
tn[i].Text = str.Name.ToString();
您将在循环的每一步中遍历xml,而不是一次
public void setlist()
{
var allPeople = xmldoc.Descendants("grand").Select(n => new person
{
name = n.Attribute("name").Value,
/*Sex = n.Attribute("sex").Value, //never used
Status = n.Attribute("status").Value, //never used*/
child = n.Attribute("child").Value,
id = n.Attribute("id").Value,
father = n.Attribute("father").Value
}).ToList();
var rootTreeNode = GetTree(allPeople, "0").First();
//do something with rootTreeNode....
}
private TreeNode[] GetTree(List<person> allPeople, string parent)
{
return allPeople.Where(p => p.father == parent).Select(p =>
{
var node = new TreeNode(p.name);
node.Tag = p;
node.Nodes.AddRange(GetTree(allPeople, p.id));
return node;
}).ToArray();
}
public void setlist()
{
var allPeople=xmldoc.substands(“grand”)。选择(n=>newperson
{
名称=n.属性(“名称”).值,
/*Sex=n.Attribute(“Sex”).Value,//从未使用过
Status=n.Attribute(“Status”).Value,//从未使用过*/
child=n.属性(“child”).值,
id=n.属性(“id”).值,
父=n.属性(“父”).值
}).ToList();
var rootTreeNode=GetTree(allPeople,“0”).First();
//用rootTreeNode做点什么。。。。
}
私有树节点[]GetTree(列出所有人,字符串父)
{
返回allPeople.Where(p=>p.father==parent)。选择(p=>
{
var节点=新的树节点(p.name);
node.Tag=p;
node.Nodes.AddRange(GetTree(allPeople,p.id));
返回节点;
}).ToArray();
}
好的,是代码说它应该抛出一个未实现的异常,删除错误并为其实现代码;)有关一般解决方案,请参阅。谢谢你,卢克布先生。这正是我想要的。非常感谢。
tn[i].Text = str.Name.ToString();
public void setlist()
{
var allPeople = xmldoc.Descendants("grand").Select(n => new person
{
name = n.Attribute("name").Value,
/*Sex = n.Attribute("sex").Value, //never used
Status = n.Attribute("status").Value, //never used*/
child = n.Attribute("child").Value,
id = n.Attribute("id").Value,
father = n.Attribute("father").Value
}).ToList();
var rootTreeNode = GetTree(allPeople, "0").First();
//do something with rootTreeNode....
}
private TreeNode[] GetTree(List<person> allPeople, string parent)
{
return allPeople.Where(p => p.father == parent).Select(p =>
{
var node = new TreeNode(p.name);
node.Tag = p;
node.Nodes.AddRange(GetTree(allPeople, p.id));
return node;
}).ToArray();
}