C# Treeview 检查节点是否存在

发布于 2024-11-08 23:39:29 字数 654 浏览 0 评论 0原文

我正在尝试从 XmlDocument 填充树视图。 树的根设置为“脚本”,从根开始,下一个级别应该是 XML 脚本内的“部门”。我可以毫无问题地从 XML 文档获取数据。我的问题是,当循环 XmlDocument 并将节点添加到根节点时,我想确保如果一个部门已经在树视图中,则不会再次添加它。我还应该补充一点,每个部门还有一个需要成为该部门的子节点的脚本列表。

到目前为止我的代码是:

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(scriptInformation);
        TreeNode t1;
        TreeNode rootNode = new TreeNode("Script View");
        treeView1.Nodes.Add(rootNode);
        foreach (XmlNode node in xDoc.SelectNodes("//row"))
        {
            t1 = new TreeNode(node["DEPARTMENT"].InnerXml);
           //How to check if node already exists in treeview?



        }

谢谢。

I'm trying to populate a treeview from an XmlDocument.
The Root of the tree is set as 'Scripts' and from the root the next level should be 'Departments' which is within the XML script. I can get data from the XML document no problem. My question is when looping through the XmlDocument and adding nodes to the root node, I want to ensure that if a department is already within the treeview then it is not added again. I should also add that each Department also has a list of scripts that need to be child nodes of the department.

My code so far is:

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(scriptInformation);
        TreeNode t1;
        TreeNode rootNode = new TreeNode("Script View");
        treeView1.Nodes.Add(rootNode);
        foreach (XmlNode node in xDoc.SelectNodes("//row"))
        {
            t1 = new TreeNode(node["DEPARTMENT"].InnerXml);
           //How to check if node already exists in treeview?



        }

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

蘸点软妹酱 2024-11-15 23:39:29
if(treeView1.Nodes.ContainsKey("DEPARTMENT")){
//...
}

编辑:递归方法:

 bool exists = false;
        foreach (TreeNode node in treeView1.Nodes) {
            if (NodeExists(node, "DEPARTMENT"))
                exists = true;
        }
    private bool NodeExists(TreeNode node, string key) {
        foreach (TreeNode subNode in node.Nodes) {
            if (subNode.Text == key) {
                return true;
            }
            if (node.Nodes.Count > 0) {
                NodeExists(node, key);
            }
        }
        return false;
    }
if(treeView1.Nodes.ContainsKey("DEPARTMENT")){
//...
}

EDIT: Recursive method:

 bool exists = false;
        foreach (TreeNode node in treeView1.Nodes) {
            if (NodeExists(node, "DEPARTMENT"))
                exists = true;
        }
    private bool NodeExists(TreeNode node, string key) {
        foreach (TreeNode subNode in node.Nodes) {
            if (subNode.Text == key) {
                return true;
            }
            if (node.Nodes.Count > 0) {
                NodeExists(node, key);
            }
        }
        return false;
    }
_畞蕅 2024-11-15 23:39:29

根据 XML 文件的大小,您可以考虑使用关联的 List 进行快速查找。当您将每个节点添加到 TreeView 时,也会将其添加到 List 中。

Depending upon the size of your XML file, you could consider using an associated List for fast lookup. As you add each node to the TreeView also add it to the List.

等往事风中吹 2024-11-15 23:39:29

如果您的 XML 文档具有固定结构,其中“部门”的索引始终为 1;

即:

index:[0] Scripts
    index:[1] Department
        index:[2] Script
    index:[1] Department2
        index:[2] Script

那么您可以将以下代码封装到一个方法中,其中“name”是字符串参数,返回类型是布尔值。

foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
    if (node.Name.ToLower() == name.ToLower()) {
        return true;
    }
}
return false;

这个想法是,在创建 TreeNode 之前,每次在 Xml 中遇到“Department”节点时,您都​​会调用该函数。

完整的示例:

private bool DepartmentNodeExists(string name) {
    foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
        if (node.Name.ToLower() == name.ToLower()) {
            return true;
        }
    }
    return false;
}

最后,简单的方法:

private bool DepartmentNodeExists(string name) {
    if (uxTreeView.Nodes[0].ContainsKey(name)) {
        return true;
    }
    else {
        return false;
    }
}

这些都只是重构并封装到它们自己的命名方法中,您当然可以只调用:

if (uxTreeView.Nodes[0].ContainsKey(name)) {
    // do not create TreeNode
}

...在解析 XML 期间。附言。这些示例都假设您已经创建了 TreeView 中的第一个根节点并将其添加到 TreeView 中。

If your XML document has a set structure where 'Departments' will always be indexed at 1;

ie:

index:[0] Scripts
    index:[1] Department
        index:[2] Script
    index:[1] Department2
        index:[2] Script

Then you could encapsulate the following code into a method where 'name' is a string parameter and the return type is boolean.

foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
    if (node.Name.ToLower() == name.ToLower()) {
        return true;
    }
}
return false;

The idea is you would call that function each time you encounter a 'Department' node in your Xml, before creating the TreeNode.

Full example:

private bool DepartmentNodeExists(string name) {
    foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
        if (node.Name.ToLower() == name.ToLower()) {
            return true;
        }
    }
    return false;
}

Lastly, the easy way:

private bool DepartmentNodeExists(string name) {
    if (uxTreeView.Nodes[0].ContainsKey(name)) {
        return true;
    }
    else {
        return false;
    }
}

These are all just refactored and encapsulated into their own named methods, you of course could just call:

if (uxTreeView.Nodes[0].ContainsKey(name)) {
    // do not create TreeNode
}

...during your parsing of your XML. PS. These examples all assume that you have the first root node in the TreeView already created and added to the TreeView.

空心↖ 2024-11-15 23:39:29

你可以这样做:

TreeNode parentNode = t1.Parent;
if (parentNode != null}
{
    if(parentNode.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        //Add node
    }
}
else
{
    bool isFound = true;
    if (treeView1.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        isFound = false;
    }

    if(!isFound)
    {
        //Add node
    }
}

You can do something like this:

TreeNode parentNode = t1.Parent;
if (parentNode != null}
{
    if(parentNode.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        //Add node
    }
}
else
{
    bool isFound = true;
    if (treeView1.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        isFound = false;
    }

    if(!isFound)
    {
        //Add node
    }
}
过期情话 2024-11-15 23:39:29

不确定文档结构...
您不能使用 Linq to Xml、加载文档并获取不同的行(行 = 部门?)并仅考虑这些元素来创建 TreeNode?它比尝试查找是否已添加具有此类文本的节点更有效。
例如:

 var rows =      (  from row  in XDocument.Load(document).Root.Elements("row")
                    select row
                 ).Distinct(new SampleElementComparerOnNameAttribute());

这里 EqualityComparer 是在“name”属性值上进行的,假设文档结构是

<rows><row name='dep1'><script>script1</script><script>script2</script></row><row name='dep1'><script>script3</script><script>script4</script></row></rows>

Not sure about the document structure...
Couldn't you use Linq to Xml, load the document and get the distinct row ( row = department?) and consider only those elements to create a TreeNode? It is more efficient than trying to find if a node with such a text has already been added.
ex:

 var rows =      (  from row  in XDocument.Load(document).Root.Elements("row")
                    select row
                 ).Distinct(new SampleElementComparerOnNameAttribute());

Here the EqualityComparer is made on the "name" attribute value assuming the doc structure to be

<rows><row name='dep1'><script>script1</script><script>script2</script></row><row name='dep1'><script>script3</script><script>script4</script></row></rows>
千柳 2024-11-15 23:39:29

我使用,

string department = node["DEPARTMENT"].InnerXml;
TreeNode node = parentNode.Nodes[department] ?? parentNode.Nodes.Add(department, department);

该行保证将首先完成对值部门的查找,如果没有找到它会创建它。您必须在 Add() 中进行双重输入,以便它具有一个键值,您可以使用 .Nodes[department] 进行查找。

I use,

string department = node["DEPARTMENT"].InnerXml;
TreeNode node = parentNode.Nodes[department] ?? parentNode.Nodes.Add(department, department);

That line guarantees that a lookup of the value department will be done first, if not found it creates it. You have to do the double entry in Add() so it will have a key value you can do the lookup with the .Nodes[department].

把时间冻结 2024-11-15 23:39:29

这取决于您输入的结构。由于您没有显示如何添加子节点,我只能向您指出 Nodes 属性,可以是 treeView1 本身,也可以是您添加的任何子节点。您应该使用 Add 方法的重载来指定键名称以简化查找。

It depends on the structure of your input. Since you don't show how exactly you add your subnodes I can only point you towards either the Contains or the ContainsKey method of the Nodes property, either of the treeView1 itself, or of any subnodes you add. You should use an overload of the Add method to specify a key name to simplify lookup.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文