C#/XML用XML文件填充TreeView

本文关键字:XML 填充 TreeView 文件 | 更新日期: 2023-09-27 18:28:43

im试图从xml文件填充树视图。

输出图像:https://i.stack.imgur.com/3HSCu.png

因此,正如您所看到的,父元素加载得很好,但子元素(元素)加载得不好。所有子节点都加载到所有父节点中。但是xml并不是这样的。

这是XML代码:

<?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>

这是C#代码:

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

C#/XML用XML文件填充TreeView

您必须仅在当前parent元素中搜索element。试试看:

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

或者更好:

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

XMLDocument.SelectNodes("toolbox/parent/element")选择文档中匹配的所有节点。您需要获取当前XmlNode的子级,而不是从XMLDocument开始。