Home  >  Article  >  Backend Development  >  Convert XML to TreeView in .net

Convert XML to TreeView in .net

巴扎黑
巴扎黑Original
2016-12-19 16:33:591584browse

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn