Binding a hierarchical xml to a tree

I have a standard winforms.NET 3.5 project. There is a tree on it. I serialized the List instance in XML using the XmlSerializer and related classes to have a hierarchical XML file.

Now I need to link this XML file to the tree in order to display all its nodes / elements (parents, children, etc.).

Is it possible to do this (LINQ or not), without the need to parse XML, etc.

thank

+5
source share
2 answers

A solution that does not need XML parsing to bind its contents to TreeView does not exist (and if it comes from the inside, of course, XML is parsed).

, 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 };
}

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 };
    }
}
+13

All Articles