简体   繁体   中英

C#/XML Populate TreeView with XML file

im trying to populate a treeview from a xml file.

Image of the output: http://i.stack.imgur.com/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);
            }
        }            
    }

You have to search for element s 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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM