结合分层XML来的TreeView [英] Binding hierarchical xml to treeview

查看:100
本文介绍了结合分层XML来的TreeView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标准的.NET 3.5 WinForms项目。它,它有一个TreeView。我已经系列化List实例转换成XML,使用的XmlSerializer和相关类,有层次的XML文件。

I have a standard .NET 3.5 winforms project. On it, it has a treeview. I have serialized a List instance into XML, using XmlSerializer and related classes, to have a hierarchical XML file.

现在,我需要把这个XML文件绑定到TreeView,以显示它的所有节点/单元(父母,子女等)的

Now, I need to bind this XML file to the treeview to display all of its nodes/elements (parents, children, etc).

有一个方便的做到这一点(LINQ与否),而不必解析XML等?

Is there a convenient to do this (LINQ or not), without having to parse XML etc?

感谢

推荐答案

这并不需要解析XML,以它的内容绑定到一个解决方案 TreeView控件 < STRONG>不存在(如果它退出,内部,的套餐的中,XML解析)。

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).

反正你会这样使用LINQ to XML实现自己:

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

而在 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 };
    }
}

这篇关于结合分层XML来的TreeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆