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
 3 using  System;
 4 using  System.Collections.Generic;
 5 using  System.ComponentModel;
 6 using  System.Data;
 7 using  System.Drawing;
 8 using  System.Text;
 9 using  System.Windows.Forms;
10
11 namespace  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}

转载于:https://www.cnblogs.com/tries/archive/2008/04/11/1147993.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值