问题:
当使用 foreach 循环在 TreeView 中显示 XML 节点的属性时,属性会为每个子节点显示,导致重复。目标是确保属性只显示一次。
示例:
<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 应该只为每个唯一的节点显示一次属性。例如,第一个 ID 为“aa”的 Host 元素的属性应该只显示一次,而不是在其子 Address 节点中重复显示。
解决方案:
以下代码解决了这个问题:
<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>
其他注意事项:
DisplayTreeView
方法中的循环中。This revised answer maintains the image and provides a more concise and clearer explanation of the code solution. The code itself is unchanged, as it was already a correct solution to the problem.
以上是解析XML时如何避免TreeView中重复的属性显示?的详细内容。更多信息请关注PHP中文网其他相关文章!