欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

.net中XML转换成TreeView视图

程序员文章站 2022-05-18 14:02:21
...
 private static void CreateTree(TreeView treeView, String xmlfile)
        {
            xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlfile); 
            try
            {
                numofChild = 0;
                treeView.Nodes.Clear();
                XmlElement rootXml = xmlDoc.DocumentElement;
                TreeNode root = new TreeNode();
                root.Text = rootXml.Name;
                treeView.Nodes.Add(root);
                if (rootXml.ChildNodes.Count > 0)
                {
                    foreach (XmlNode subXmlnode in rootXml.ChildNodes)
                    {
                        TreeNode treenode = new TreeNode();
                        treenode.Text = "<" + subXmlnode.Name + ">";
                        root.Nodes.Add(treenode);
                        AddNodeToTreeView(subXmlnode.ChildNodes, treenode);
                    }
                }
                else
                {
                    root.Text = rootXml.Value;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static void AddNodeToTreeView(XmlNodeList xmlNodeList, TreeNode parentNode)
        {
            foreach (XmlNode xmlnode in xmlNodeList)
            {
                TreeNode subtreenode = new TreeNode();
                subtreenode.Text = "<" + xmlnode.Name + ">";
                parentNode.Nodes.Add(subtreenode);
                if (xmlnode.ChildNodes.Count > 0)
                {
                    AddNodeToTreeView(xmlnode.ChildNodes, subtreenode);
                }
                else
                {
                    subtreenode.Text = xmlnode.Value;
                }
            }           
        }