C# xml內容繫結treeview
阿新 • • 發佈:2019-01-11
private void button1_Click(object sender, EventArgs e)
{
string filepath=Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory )+"\\11.xml";
if (File.Exists(filepath ))
{
XmlDocument xld=new XmlDocument() ;
xld.Load(filepath );
RecursionTreeControl(xld.DocumentElement, treeView1.Nodes);
treeView1.ExpandAll(); //展開TreeView控制元件中的所有項
}
{
string filepath=Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory )+"\\11.xml";
if (File.Exists(filepath ))
{
XmlDocument xld=new XmlDocument() ;
xld.Load(filepath );
RecursionTreeControl(xld.DocumentElement, treeView1.Nodes);
treeView1.ExpandAll(); //展開TreeView控制元件中的所有項
}
}
private void RecursionTreeControl(XmlNode xmlNode, TreeNodeCollection nodes)
{
foreach (XmlNode node in xmlNode.ChildNodes) //迴圈遍歷當前元素的子元素集合
{
string temp = (node.Value != null ? node.Value : (node.Attributes != null && node.Attributes.Count > 0) ? node.Attributes[0].Value : node.Name);
TreeNode new_child = new TreeNode(temp); //定義一個TreeNode節點物件
nodes.Add(new_child); //向當前TreeNodeCollection集合中添加當前節點
RecursionTreeControl(node, new_child.Nodes); //呼叫本方法進行遞迴
}
}