根据树视图中的选择查找xml节点

时间:2016-11-25 16:10:06

标签: c# xml treeview

在我目前的项目(winform)中,我正在使用xml提供树视图。 像这个例子一样构建xml:

<Root>
  <ns code="NS" description=" - New">
    <someName code="5M" description=" - some 5M">
      <entry1 code="TN" description=" - some description 1" />
      <entry2 code="TO" description=" - some description 2" />
    </someName>
	<someOtherName code="6M" description=" - some 6M">
		<entry1 code="TN" description=" - some description 1" />
		<entry2 code="TO" description=" - some description 2" />
	</someOtherName>
  </ns>
</Root>

我根据代码和描述填充我的树视图,因此树视图如下所示: enter image description here

但现在我可以根据树视图中的选定节点向xml添加节点。

现在我想知道,是否有可能根据所选的Treenode(基于非唯一属性)获取xmlNode。

实现这一目标的最佳做法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用所选树节点的属性“FullPath”:

  private void trvAcsConfig_AfterSelect(object sender, TreeViewEventArgs e)
    {
        try
        {
            //get selected tree node
            TreeNode selectedTreeNOde = ((TreeView)sender).SelectedNode;

            string fullPath = "/" + selectedTreeNOde.FullPath.Replace("\\", "/");

            //selected tree node is an attribute, comment,... 
            if (selectedTreeNOde.Nodes.Count == 0)
                fullPath = fullPath.Substring(0, fullPath.LastIndexOf('/'));


            XmlNodeList nodes = AcsConfig.ConfigXmlDocument.SelectNodes(fullPath);

            Console.WriteLine(selectedTreeNOde.Name);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }