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

窗体类代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TreeView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Xml.XmlDocument document =
            new System.Xml.XmlDataDocument();
            document.Load(@"C:/test/C#/TreeView/TreeView/TreeView/contacts.xml");

            populateTreeControl(document.DocumentElement,
            this.tvPerson.Nodes);
        }

        private void populateTreeControl(
       System.Xml.XmlNode document,
       System.Windows.Forms.TreeNodeCollection nodes)
        {
            foreach (System.Xml.XmlNode node in
            document.ChildNodes)
            {
                // If the element has a value, display it;
                // otherwise display the first attribute
                // (if there is one) or the element name
                // (if there isn't)

                string text = (node.Value != null ? node.Value :
                (node.Attributes != null &&
                node.Attributes.Count > 0) ?
                node.Attributes[0].Value : node.Name);
                TreeNode new_child = new TreeNode(text);

                nodes.Add(new_child);
                populateTreeControl(node, new_child.Nodes);
            }
        }
    }

测试 xml 



 
   
     
        someone@some_pop_mail.net
     

      Edinburgh
      United Kingdom
   

   
     
        someone@some_web_mail.net
     

      Papakura
      New Zealand
   

   
     
        someone_else@some_web_mail.com
     

      Muriwai
      New Zealand
   

 

 

 

你可能感兴趣的:(winform,xml,文档,email,encoding,null)