C# TreeView绑定 能展示xml属性

来源:互联网 发布:希捷硬盘数据恢复软件 编辑:程序博客网 时间:2024/04/26 16:26

//加载XML文件,并在TreeView上显示

        public void loadXML(Stringpath)

        {

            try

            {

                this.Cursor =Cursors.WaitCursor;

                XmlDocumentxDoc =newXmlDocument();

                xDoc.Load(path);

                XMLTree.Nodes.Clear();

                XMLTree.Nodes.Add(new  TreeNode(xDoc.DocumentElement.Name));

                TreeNodetNode =newTreeNode();

                tNode= (TreeNode)XMLTree.Nodes[0];

                addTreeNode(xDoc.DocumentElement,tNode);

                XMLTree.ExpandAll();

            }

            catch(XmlExceptionxExc)

            {

                MessageBox.Show(xExc.Message);

            }

            catch(Exceptionex)

            {

                MessageBox.Show(ex.Message);

            }

            finally

            {

                this.Cursor =Cursors.Default;//Change thecursor back

            }

        }

        privatevoidaddTreeNode(XmlNodexmlNode,TreeNodetreeNode)

        {

            XmlNodexNode;

            TreeNodetNode;

            XmlNodeListxNodeList;

 

            inti = 0;

            boolHaveAttributes =false;

            //先处理属性

            if(xmlNode.Attributes!=null)

            {

                if(xmlNode.Attributes.Count > 0)

                {

                    HaveAttributes=true;

                    for(; i < xmlNode.Attributes.Count; ++i)

                    {

                        treeNode.Nodes.Add(newTreeNode(xmlNode.Attributes.Item(i).Name));

                        tNode = treeNode.Nodes[i];

                        tNode.Nodes.Add(xmlNode.Attributes.Item(i).Value);

                    }

                }

            }

            //再处理子节点

            if(xmlNode.HasChildNodes)//The current node has children

            {

                xNodeList= xmlNode.ChildNodes;

                for(intx=0;x <=xNodeList.Count - 1;x++)

                {

                    xNode= xmlNode.ChildNodes[x];

 

 

                    treeNode.Nodes.Add(newTreeNode(xNode.Name));

                    tNode= treeNode.Nodes[x+i];

                    addTreeNode(xNode,tNode);

                }

            }

            elseif (!HaveAttributes)

            {//既无子节点也无属性,写注释           

                 treeNode.Text =xmlNode.OuterXml.Trim();

            }

 

        }