加载到树视图时过滤XML标记

时间:2009-05-12 07:01:30

标签: c# .net xml treeview

我正在尝试将XML文件加载到树视图控件中,对其进行编辑并将其保存为其他XML格式。

<MyConfig>
  <description>
    <![CDATA[Add All config data]]>
  </description>
  <group name="Server">
    <description>
      <![CDATA[Server info]]>
    </description>
    <parameter name="Host" type="string">
      <description>
        <![CDATA[Host Name]]>
      </description>
      <value>cccc.ac.lk</value>
    </parameter>
    <parameter name="Port" type="integer">
      <description>
        <![CDATA[port no]]>
      </description>
      <range>0-65536</range>
      <value>47110</value>
    </parameter>
  </group>
</MyConfig>

我使用以下方法加载XML数据

private void populateTreeControl(System.Xml.XmlNode document, 
System.Windows.Forms.TreeNodeCollection nodes)
{
  foreach (System.Xml.XmlNode node in document.ChildNodes)
  {
    string text = (node.Value != null ? node.Value : 
      (node.Attributes != null && node.Attributes.Count > 0) ? 
        node.Attributes[0].Value : node.Name);
    TreeNode new_child = new TreeNode(text);
    nodes.Add(new_child);
    populateTreeControl(node, new_child.Nodes);
  }
}

现在我想过滤掉一些节点并将其加载到树视图中。作为一个例子,在上面的例子中加载描述标签等是没用的。我只想用MyConfig创建树 - &gt;组 - &gt;服务器---&GT;主机和MyConfig - &gt;组 - &gt;服务器---&GT;端口

我应该如何修改populateTreeControl()方法以获得此功能?

1 个答案:

答案 0 :(得分:1)

private void populateTreeControl(
  System.Xml.Node context, 
  System.Windows.Forms.TreeNodeCollection treeNodes,
  List<string> xpath,
  int depth
)
{
  if (xpath.Count > depth) {
    foreach (System.Xml.XmlNode xmlNode in context.SelectNodes(xpath[depth]))
    {
      string text = "";
      if (xmlNode.Value != null) 
        text = xmlNode.Value;
      else if (xmlNode.Attributes.Count > 0)
        text = xmlNode.Attributes[0].Value;
      else 
        text = xmlNode.Name;

      TreeNode new_child = new TreeNode(text);
      treeNodes.Add(new_child);

      populateTreeControl(xmlNode, new_child.Nodes, xpath, depth + 1);
    }
  }
}

打电话给

List<string> xpath = new List<string>();
xpath.Add("/MyConfig/group/[@name='Server']");
xpath.Add("parameter[@name='Host' or @name='Port']");

populateTreeControl(xmlDoc, tree.Nodes, xpath, 0);