winform实现 绑定xml文档到treeview 控件

 1测试 xml 
 2
 3<?xml version="1.0" encoding="utf-8" ?>
 4<addressbook>
 5  <contacts id="Contacts">
 6    <contact id="Alex">
 7      <email id="popmail">
 8        someone@some_pop_mail.net
 9      </email>
10      <city>Edinburgh</city>
11      <country>United Kingdom</country>
12    </contact>
13    <contact id="Rebekah">
14      <email id="webmail">
15        someone@some_web_mail.net
16      </email>
17      <city>Papakura</city>
18      <country>New Zealand</country>
19    </contact>
20    <contact id="Justin">
21      <email id="webmail">
22        someone_else@some_web_mail.com
23      </email>
24      <city>Muriwai</city>
25      <country>New Zealand</country>
26    </contact>
27  </contacts>
28</addressbook>
 1窗体类代码:
 2
 3using System;
 4using System.Collections.Generic;
 5using System.ComponentModel;
 6using System.Data;
 7using System.Drawing;
 8using System.Text;
 9using System.Windows.Forms;
10
11namespace TreeView
12{
13    public partial class Form1 : Form
14    {
15        public Form1()
16        {
17            InitializeComponent();
18        }

19
20        private void Form1_Load(object sender, EventArgs e)
21        {
22            System.Xml.XmlDocument document =
23            new System.Xml.XmlDataDocument();
24            document.Load(@"C:\test\C#\TreeView\TreeView\TreeView\contacts.xml");
25
26            populateTreeControl(document.DocumentElement,
27            this.tvPerson.Nodes);
28        }

29
30        private void populateTreeControl(
31       System.Xml.XmlNode document,
32       System.Windows.Forms.TreeNodeCollection nodes)
33        {
34            foreach (System.Xml.XmlNode node in
35            document.ChildNodes)
36            {
37                // If the element has a value, display it;
38                // otherwise display the first attribute
39                // (if there is one) or the element name
40                // (if there isn't)
41
42                string text = (node.Value != null ? node.Value :
43                (node.Attributes != null &&
44                node.Attributes.Count > 0?
45                node.Attributes[0].Value : node.Name);
46                TreeNode new_child = new TreeNode(text);
47
48                nodes.Add(new_child);
49                populateTreeControl(node, new_child.Nodes);
50            }

51        }

52    }

53}

posted @ 2008-04-11 10:41  jdkbean  阅读(659)  评论(0编辑  收藏  举报