user2708135
user2708135

Reputation: 13

C#/XML Populate TreeView with XML file

im trying to populate a treeview from a xml file.

Image of the output: https://i.sstatic.net/3HSCu.png

So as you can see the parents are loaded well, but the childs (the elements) not. All the child nodes are loaded in all parent nodes. But the xml is not like that.

This is the XML code:

<?xml version="1.0" encoding="utf-8" ?> 
<toolbox>
<parent id="p1" caption="All Elements" class="parent">
  <element id="1" name="Button" />
  <element id="2" name="Label" />
  <element id="3" name="Inputfield" />
  <element id="4" name="Textarea" />
  <element id="5" name="Image" />
  <element id="6" name="Background" />
  <element id="7" name="TreeView" />
</parent>
<parent id="p2" caption="Some Elements 1" class="parent">
  <element id="1" name="Button" />
  <element id="2" name="Label" />
  <element id="3" name="Inputfield" />
</parent>
<parent id="p3" caption="Some Elements 2" class="parent">
  <element id="4" name="Textarea" />
  <element id="5" name="Image" />
  <element id="6" name="Background" />
  <element id="7" name="TreeView" />
</parent>
</toolbox>

This is the C# code:

    public void loadElements(string XML_Elements, TreeView Elements_Tree){
        XmlDocument XMLDocument =  new XmlDocument();
        XMLDocument.Load(XML_Elements);

        Elements_Tree.Nodes.Clear();
        Elements_Tree.BeginUpdate();

        XmlNodeList XMLParent = XMLDocument.SelectNodes("toolbox/parent"); 
        foreach(XmlNode xmlparent in XMLParent){
            //add parents
            string Parent_Caption = xmlparent.Attributes["caption"].Value;
            TreeNode parents = Elements_Tree.Nodes.Add(Parent_Caption);

            //add childs
            XmlNodeList XMLChilds = XMLDocument.SelectNodes("toolbox/parent/element");
            foreach (XmlNode xmlchild in XMLChilds)
            {
                string Child_Name = xmlchild.Attributes["name"].Value;
                parents.Nodes.Add(Child_Name);
            }
        }            
    }

Upvotes: 1

Views: 4214

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You have to search for elements only within current parent element. Try that:

XmlNodeList XMLChilds = XMLDocument.SelectNodes("toolbox/parent[@caption='" + Parent_Caption  + "']/element");

Or maybe even better:

XmlNodeList XMLChilds = xmlparent.SelectNodes("element");

Upvotes: 1

Alex Paven
Alex Paven

Reputation: 5549

XMLDocument.SelectNodes("toolbox/parent/element") selects all nodes that match in the document. You need to get the children of the current XmlNode, not start at the XMLDocument.

Upvotes: 0

Related Questions