CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

XML to Treeview
Submitted By jeeva jagadesh
On 9/6/2009 6:33:41 AM
Tags: asp.net,CodeDigest  

 public void DeserializeTreeView(TreeView treeView, string fileName)
        {
            
            XmlTextReader reader = null;
            try
            {
                // disabling re-drawing of treeview till all nodes are added
                treeView.BeginUpdate();

                reader =
                    new XmlTextReader(fileName);

                TreeNode parentNode = null;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {


                        TreeNode newNode = new TreeNode();
                        bool isEmptyElement = reader.IsEmptyElement;

                        newNode.Text = reader.Name;
                       
                        // add new node to Parent Node or TreeView
                        if (parentNode != null)
                            parentNode.Nodes.Add(newNode);
                        else
                            treeView.Nodes.Add(newNode);

                        // making current node 'ParentNode' if its not empty
                        if (!isEmptyElement)
                        {
                            parentNode = newNode;
                        }
                    }
                    // moving up to in TreeView if end tag is encountered
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {


                        parentNode = parentNode.Parent;

                    }
                    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
                    { //Ignore Xml Declaration                   
                    }
                    else if (reader.NodeType == XmlNodeType.None)
                    {
                        return;
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        parentNode.Nodes.Add(reader.Value);
                        
                    }

                }
            }
            finally
            {

                treeView.EndUpdate();
                reader.Close();
            }

        }

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..