treeView绑定XML文档

 在家这两天,共装了两遍系统(郁闷啊。。),现在不能连adsl网络的问题终于解决了(原来是网卡驱动的问题,我晕啊)!!呵呵废话不多说了。要想让treeView绑定XML文档,只需编写一个递归过程就行了。XML代码如下:

<?xml version="1.0" encoding="utf-8" ?>
 
<!-- 注意:treeview 为根结点,nodes 为父级节点,node 为子节点。
  
-->
<treeview>
 
<nodes>
    
<name>根节点1</name>
    
<zuozhe />
    
<liupai />
    
<link />
  
<node>
      
<name>测试节点1 -1</name>
      
<zuozhe />
      
<liupai />
    
</node>
    
<node>
      
<name>测试节点1 -2</name>
      
<zuozhe />
      
<liupai />
      
<link />
    
</node>
  
</nodes>

在页面中加一个TreeView控件和一个button控件。写一个递归过程如下:

/// <summary>
        /// 构建树。遍历XML所有的节点
        /// 
</summary>
        /// 
<param name="XMLNodes">XML节点</param>
        /// 
<param name="TreeNode">树的当前节点</param>
        private void BuildTree(XmlNodeList XMLNodes, TreeNodeCollection treeNodes)
        {
            string sValue;
            for (int i = 0; i 
< XMLNodes.Count; i++)
            {
                if (XMLNodes[i].NodeType 
== XmlNodeType.Element)
                {
                    TreeNode tNode 
= new TreeNode();
                    sValue 
= "";
                    if (XMLNodes[i].HasChildNodes && XMLNodes[i].ChildNodes.Count 
== 1 && XMLNodes[i].ChildNodes[0].NodeType == XmlNodeType.Text)
                    {
                        sValue 
= XMLNodes[i].ChildNodes[0].Value;
                    
}
                    else
                    {
                        for (int j 
= 0; j < XMLNodes[i].Attributes.Count; j++)
                        {
                            sValue +
= XMLNodes[i].Attributes[j].Name + "=" + XMLNodes[i].Attributes[j].Value + ";";
                        }
                    }
                    if (sValue 
== "")
                    {
                        tNode.Text 
= XMLNodes[i].Name;
                    
}
                    else
                    {
                        tNode.Text 
= XMLNodes[i].Name + ":" + sValue;
                    }
                    treeNodes.Add(tNode);
                    if(XMLNodes[i].HasChildNodes)
                    {
                        BuildTree(XMLNodes[i].ChildNodes, tNode.Nodes);

                    }

                }

          

双击button,加入以下代码:
private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument doc=new XmlDocument();
            doc.Load(@"C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\XMLFile1.xml");                       
            BuildTree(doc.ChildNodes, treeView1.Nodes); ||调用递归
          
        }
posted @ 2008-05-23 09:00  浪子の无悔  阅读(279)  评论(0编辑  收藏  举报