Binding hierarchical xml to treeview

A solution that doesn’t need to parse XML in order to bind its contents to a TreeView doesn’t exist (and if it exits, internally, of course, XML is parsed).

Anyway you could implement this yourself by using LINQ to XML:

private void Form1_Load(object sender, EventArgs e)
{
    var doc = XDocument.Load("data.xml");
    var root = doc.Root;
    var x = GetNodes(new TreeNode(root.Name.LocalName), root).ToArray();

    treeView1.Nodes.AddRange(x);
}

private IEnumerable<TreeNode> GetNodes(TreeNode node, XElement element)
{
    return element.HasElements ?
        node.AddRange(from item in element.Elements()
                      let tree = new TreeNode(item.Name.LocalName)
                      from newNode in GetNodes(tree, item)
                      select newNode)
                      :
        new[] { node };
}

And in TreeNodeEx:

public static class TreeNodeEx
{
    public static IEnumerable<TreeNode> AddRange(this TreeNode collection, IEnumerable<TreeNode> nodes)
    {
        var items = nodes.ToArray();
        collection.Nodes.AddRange(items);
        return new[] { collection };
    }
}

Leave a Comment