Display the XML attribute in Treeview, avoid repeating
When using the Foreach cycle to display the attribute of the XML node in the Treeview, the attribute is displayed for each sub -node, which causes duplication. The goal is to ensure that the attribute is only displayed once.
Example:
Expected behavior:
<code class="language-xml"><dataconfiguration><hosts><site name="ss"><host id="aa"><address host="www.www.com"></address> </host><host id="ee"><address host="www.www.com"></address> </host></site></hosts></dataconfiguration></code>
TreeView should only display the attribute for each unique node. For example, the attribute of the HOST element of the first ID of "AA" should be displayed only once, not repeatedly displayed in its subdress node. Solution:
The following code solves this problem:
Before the iterative child node, the code checks whether the current node has attributes. If there is any attribute, add them to the node text only once.
Then execute the cycle of the calendar node and add each child node to the timeView.
<code class="language-csharp">private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode) { XmlNode xNode; TreeNode tNode; XmlNodeList nodeList; int i; // 循环遍历 XML 节点,直到到达叶子节点。 // 在循环过程中将节点添加到 TreeView。 if (inXmlNode.HasChildNodes) { // 检查 XmlNode 是否具有属性 if (inXmlNode.Attributes.Count != 0) { foreach (XmlAttribute att in inXmlNode.Attributes) { inTreeNode.Text += " " + att.Name + ": " + att.Value; } } nodeList = inXmlNode.ChildNodes; for (i = 0; i < nodeList.Count; i++) { xNode = nodeList.Item(i); tNode = new TreeNode(xNode.Name); inTreeNode.Nodes.Add(tNode); AddNode(xNode, tNode); } } }</code>
If you need to display the XML statement in the TreeView, add it to the loop in the method.
The above is the detailed content of How to Avoid Duplicate Attribute Display in a TreeView When Parsing XML?. For more information, please follow other related articles on the PHP Chinese website!