using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace LoadTreeViewFromXml
{
    public static class TreeViewExtensions
    {
        // Load a TreeView control from an XML file.
        public static void LoadFromXmlFile(this TreeView trv, string filename)
        {
            // Load the XML document.
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filename);

            // Add the root node's children to the TreeView.
            trv.Nodes.Clear();
            AddTreeViewChildNodes(trv.Nodes, xmlDoc.DocumentElement);
        }

        // Add the children of this XML node to this child nodes collection.
        private static void AddTreeViewChildNodes(TreeNodeCollection parentNodes, XmlNode xmlNode)
        {
            foreach (XmlNode xmlChild in xmlNode.ChildNodes)
            {
                // Make the new TreeView node.
                TreeNode newNode = parentNodes.Add(xmlChild.Name);

                // Recursively load this node's descendants.
                AddTreeViewChildNodes(newNode.Nodes, xmlChild);
            }
        }
    }
}
