Home > Backend Development > C++ > How to Avoid Duplicate Attribute Display When Parsing XML into a C# TreeView?

How to Avoid Duplicate Attribute Display When Parsing XML into a C# TreeView?

Barbara Streisand
Release: 2025-01-27 11:51:09
Original
321 people have browsed it

How to Avoid Duplicate Attribute Display When Parsing XML into a C# TreeView?

The method of analyzing the XML file contained in attributes in C# to the method of analysis of the attribute to the TreeView control

Question:

When using the Foreach cycle to parse the XML file containing attributes, the attributes will be displayed multiple times. How to modify the code to display only one attribute?

Solution:

Only display only one attribute in the TreeView control:

Explanation:

private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
    if (inXmlNode.HasChildNodes)
    {
        // 检查 XmlNode 是否具有属性
        string attributes = "";
        foreach (XmlAttribute att in inXmlNode.Attributes)
        {
            attributes += " " + att.Name + ": " + att.Value;
        }
        if (!string.IsNullOrEmpty(attributes))
        {
            inTreeNode.Text += attributes;
        }


        foreach (XmlNode node in inXmlNode.ChildNodes)
        {
            TreeNode newNode = inTreeNode.Nodes.Add(node.Name);
            AddNode(node, newNode);
        }
    }
}
Copy after login
The updated code moves the attribute loop outside the sub -node cycle. This can ensure that even if there are multiple sub -nodes under the parent node, the attributes are only displayed once. The improved code uses the string variable

to accumulate all the attributes, and then add it to at one time to avoid repeatedly added.

The above is the detailed content of How to Avoid Duplicate Attribute Display When Parsing XML into a C# TreeView?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template