xml文档绑定某个属性值到treeview算法

原文发布时间为:2008-08-10 —— 来源于本人的百度文章 [由搬家工具导入]


using System.Xml;

protected void Button2_Click(object sender, EventArgs e)
    {
        string xmlpath = Server.MapPath("~/App_Data/dirList.xml");
        if (File.Exists(xmlpath))
        {
            XmlDocument dom = new XmlDocument();
            dom.Load(xmlpath);
            TreeView1.Nodes.Clear();

            BindXmlToTreeView(dom.DocumentElement.ChildNodes, TreeView1.Nodes);
        }
        else
        {
            Response.Write("<script>alert('XML文档不存在,请先创建')</script>");
        }
    }

    protected void BindXmlToTreeView(XmlNodeList xmlnodes, TreeNodeCollection treeNodes)
    {
        foreach (XmlNode child in xmlnodes)
        {
            if (child.Attributes != null && child.Attributes.Count > 0)//这个判断很重要!
            {
                string treeText = child.Attributes["name"].Value;
                TreeNode tn = new TreeNode(treeText);
                treeNodes.Add(tn);
                BindXmlToTreeView(child.ChildNodes, tn.ChildNodes);
            }
        }
    }

-----------------------------------------

原算法:

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);     

}  

}

原文地址:https://www.cnblogs.com/handboy/p/7141594.html