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 };
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…