递归XML加载WinForm Treeview(原创)
时间:2011-01-04 来源:roby
<?xml version="1.0" encoding="utf-8" ?> <root name="rootNode" text="根节点"> <node name="node1" text="节点1"> <childNode name="childNode1" text="子节点1"> <grandchild name="grandchild1" text="子子节点1"></grandchild> <grandchild name="grandchild2" text="子子节点2"></grandchild> <grandchild name="grandchild3" text="子子节点3"></grandchild> <grandchild name="grandchild4" text="子子节点4"></grandchild> </childNode> <childNode name="childNode1" text="子节点1"></childNode> <childNode name="childNode2" text="子节点2"></childNode> </node> <node name="node2" text="节点2"> <childNode name="childNode1" text="子节点1"></childNode> <childNode name="childNode2" text="子节点2"></childNode> <childNode name="childNode3" text="子节点3"></childNode> </node> <node name="node3" text="节点3"> <childNode name="childNode1" text="子节点1"></childNode> <childNode name="childNode2" text="子节点2"></childNode> <childNode name="childNode3" text="子节点3"></childNode> </node> <node name="node4" text="节点4"> <childNode name="childNode1" text="子节点1"></childNode> <childNode name="childNode2" text="子节点2"></childNode> <childNode name="childNode3" text="子节点3"></childNode> </node> </root>
将这个xml文件加载到Winform的treeview上
后台代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Xml; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); XmlDocument doc = new XmlDocument(); try { string path = AppDomain.CurrentDomain.BaseDirectory + "XMLFile1.xml"; doc.Load(path); treeView1.BeginUpdate(); XmlElement xe = (XmlElement)doc.SelectSingleNode("root"); TreeNode root = new TreeNode(); root.Name = xe.GetAttribute("name"); root.Text = xe.GetAttribute("text"); root = GetChildNodes(xe, root); treeView1.Nodes.Add(root); treeView1.EndUpdate(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } public TreeNode GetChildNodes(XmlElement xe, TreeNode upNode) { if (xe.HasChildNodes) { foreach (XmlNode node in xe.ChildNodes) { XmlElement xlt = (XmlElement)node; TreeNode tn = new TreeNode(); tn.Text = xlt.GetAttribute("text"); tn.Name = xlt.GetAttribute("name"); GetChildNodes(xlt, tn); upNode.Nodes.Add(tn); } } return upNode; } } }
效果如下图:
相关阅读 更多 +
排行榜 更多 +