I'm creating a XML-viewer which should be able to read every XML file and put it in a treeview.
My goal is to create a XMLViewer control, an user should be able to change certain routines in his own implementations. I provide default implementations that offer a basic functionality so that the XML viewer at least shows a default behaviour.

What I have so far:

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "XML Files|*.xml";
            ofd.InitialDirectory = @"C:\";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = ofd.FileName.ToString();

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(ofd.FileName);
                treeView1.Nodes.Clear();
                treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));
                TreeNode tNode = new TreeNode();
                tNode = (TreeNode)treeView1.Nodes[0];

                addTreeNode(xDoc.DocumentElement, tNode);
                treeView1.ExpandAll();   
            }    
        }

        private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;
                for (int x = 0; x <= xNodeList.Count - 1; x++)
                {
                    xNode = xmlNode.ChildNodes[x];

                    treeNode.Nodes.Add(new TreeNode(xNode.Name));
                    treeNode.ForeColor = Color.Red;
                    tNode = treeNode.Nodes[x];

                    tNode.ForeColor = Color.Green;
                    addTreeNode(xNode, tNode);                    
                }
            }
            else 
                treeNode.Text = xmlNode.OuterXml.Trim();
        }

Results in:

viewer

What I want:

xmlviewer

Any ideas? :)
Thanks in advance!

I'm assumng that you want the value of the last child, in a branch, to be added to it's parent, instead of being put in a new node. Perhaps replacing line 40 with the following will work:

if (xnode(HasChildrenNodes)
    addTreeNode(xNode, tNode);  
else
    xmlNode.value = xmlNode.value + " " + xNode.value;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.