Is it possible to bind XElemnt from XML to each treeView node? In the Nodes.Add method I did not find the binding of objects. Maybe I missed something ...?

For example, I want to display all its attributes somewhere when selecting a node name from a tree. Or do I have to do any sampling from the source XML?

    1 answer 1

    It all depends on the structure of the source XML and on the form in which you need to get the data.

    Suppose there is a document with information about people of the following content:

    <Persons> <Person id="1"> <FirstName>Вася</FirstName> <LastName>Пупкин</LastName> <Address Country="РФ"> <City>Тагил</City> <Street>Ленина</Street> </Address> </Person> <Person id="007"> <FirstName>James</FirstName> <LastName>Bond</LastName> <Address Country="UK"> <City>London</City> <Street>Lennon</Street> </Address> </Person> </Persons> 

    Apply classic tree traversal:

     void WalkTree(TreeNodeCollection nodes, XElement element) { if (element.HasElements) { var node = nodes.Add(element.Name.LocalName); foreach (var attr in element.Attributes()) node.Nodes.Add(attr.Value); foreach (var elem in element.Elements()) WalkTree(node.Nodes, elem); } else nodes.Add(element.Value); } 

    We use:

     var doc = XDocument.Load("test.xml"); WalkTree(treeView.Nodes, doc.Root); treeView.ExpandAll(); 

    In this case, I take the name of the elements that have descendants, and then pass on their descendants. And for each leaf element that has no descendants, I bring up the value in the tree. Attributes are equivalent to leaf elements.

    You can vary the code as you like.

    • Little, not that I want. I want something like when working with components that have a DataSource. Ie I can connect any object and indicate what the user will imagine. - iluxa1810
    • @ iluxa1810 - I understand what I want. But, there is no such binding for a tree. It is necessary either to look for a third-party component, or to write the code yourself, since it is simple. - Alexander Petrov