XMLFile1.xml文件如下:
view source print?
01
|
<?xml version="1.0" encoding="utf-8" ?>
|
02
|
<root name="rootNode" text="根节点">
|
03
|
<node name="node1" text="节点1">
|
04
|
<childNode name="childNode1" text="子节点1">
|
05
|
<grandchild name="grandchild1" text="子子节点1"></grandchild>
|
06
|
<grandchild name="grandchild2" text="子子节点2"></grandchild>
|
07
|
<grandchild name="grandchild3" text="子子节点3"></grandchild>
|
08
|
<grandchild name="grandchild4" text="子子节点4"></grandchild>
|
10
|
<childNode name="childNode1" text="子节点1"></childNode>
|
11
|
<childNode name="childNode2" text="子节点2"></childNode>
|
13
|
<node name="node2" text="节点2">
|
14
|
<childNode name="childNode1" text="子节点1"></childNode>
|
15
|
<childNode name="childNode2" text="子节点2"></childNode>
|
16
|
<childNode name="childNode3" text="子节点3"></childNode>
|
18
|
<node name="node3" text="节点3">
|
19
|
<childNode name="childNode1" text="子节点1"></childNode>
|
20
|
<childNode name="childNode2" text="子节点2"></childNode>
|
21
|
<childNode name="childNode3" text="子节点3"></childNode>
|
23
|
<node name="node4" text="节点4">
|
24
|
<childNode name="childNode1" text="子节点1"></childNode>
|
25
|
<childNode name="childNode2" text="子节点2"></childNode>
|
26
|
<childNode name="childNode3" text="子节点3"></childNode>
|
将这个xml文件加载到Winform的treeview上
后台代码如下:
view source print?
02
|
using System.Collections.Generic;
|
03
|
using System.ComponentModel;
|
07
|
using System.Windows.Forms;
|
10
|
namespace WindowsApplication1
|
12
|
public partial class Form1 : Form
|
16
|
InitializeComponent();
|
18
|
XmlDocument doc = new XmlDocument();
|
22
|
string path = AppDomain.CurrentDomain.BaseDirectory + "XMLFile1.xml";
|
24
|
treeView1.BeginUpdate();
|
25
|
XmlElement xe = (XmlElement)doc.SelectSingleNode("root");
|
26
|
TreeNode root = new TreeNode();
|
27
|
root.Name = xe.GetAttribute("name");
|
28
|
root.Text = xe.GetAttribute("text");
|
29
|
root = GetChildNodes(xe, root);
|
30
|
treeView1.Nodes.Add(root);
|
31
|
treeView1.EndUpdate();
|
35
|
MessageBox.Show(ex.ToString());
|
39
|
public TreeNode GetChildNodes(XmlElement xe, TreeNode upNode)
|
43
|
foreach (XmlNode node in xe.ChildNodes)
|
45
|
XmlElement xlt = (XmlElement)node;
|
46
|
TreeNode tn = new TreeNode();
|
47
|
tn.Text = xlt.GetAttribute("text");
|
48
|
tn.Name = xlt.GetAttribute("name");
|
49
|
GetChildNodes(xlt, tn);
|
效果如下图: