Tuesday, September 22, 2009

Binding an XML to TreeView using C#

Here is the code for binding an XML to TreeView control


private void button1_Click(object sender, EventArgs e)
        {
            inputFile.ShowDialog();
            txtInputFile.Text = inputFile.FileName;
        }


private void updateTreeView(string filename)
        {
            try
            {
                txtInputFile.Text = filename;
                tvXMLView.Nodes.Clear();
                tmpxmldoc = new XmlDocument();
                tmpxmldoc.Load(filename);
                FillTree(tmpxmldoc.DocumentElement, tvXMLView.Nodes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void FillTree(XmlNode node, TreeNodeCollection parentnode)
        {
            // End recursion if the node is a text type
            if (node == null || node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA)
                return;

            TreeNodeCollection tmptreenodecollection = AddNodeToTree(node, parentnode);

            // Add all the children of the current node to the treeview
            foreach (XmlNode tmpchildnode in node.ChildNodes)
            {
                FillTree(tmpchildnode, tmptreenodecollection);
            }
        }


        private TreeNodeCollection AddNodeToTree(XmlNode node, TreeNodeCollection parentnode)
        {
            TreeNode newchildnode = CreateTreeNodeFromXmlNode(node);

            // if nothing to add, return the parent item
            if (newchildnode == null) return parentnode;

            // add the newly created tree node to its parent
            if (parentnode != null) parentnode.Add(newchildnode);

            return newchildnode.Nodes;
        }


        private TreeNode CreateTreeNodeFromXmlNode(XmlNode node)
        {
            TreeNode tmptreenode = new TreeNode();

            if ((node.HasChildNodes) && (node.FirstChild.Value != null))
            {
                tmptreenode = new TreeNode(node.Name);
                //TreeNode tmptreenode2 = new TreeNode(node.FirstChild.Value);
                //tmptreenode.Nodes.Add(tmptreenode2);
            }
            else if (node.NodeType != XmlNodeType.CDATA)
            {
                tmptreenode = new TreeNode(node.Name);
            }

            return tmptreenode;
        }

1 comment: