这是我为您提供的解决方案:
private TreeNode[] FindTreeNodes(string Key)
{
return oTreeView.Nodes.Find(Key, true);
}
private void LoadTreeview(string XmlFile)
{
oTreeView.Nodes.Clear();
if (File.Exists(XmlFile) == true)
{
XmlDocument oXmlDocument = new XmlDocument();
oXmlDocument.Load(XmlFile);
XmlNodeList oXmlNodeList = oXmlDocument.SelectNodes("/Processes/Process");
foreach (XmlNode oXmlNode in oXmlNodeList)
{
int iID = Convert.ToInt32(oXmlNode.Attributes["id"].Value);
string sName = oXmlNode.Attributes["name"].Value;
int iParentID = Convert.ToInt32(oXmlNode.Attributes["ParentPID"].Value);
TreeNode[] oParentNodes = FindTreeNodes(iParentID.ToString());
if (oParentNodes.Length == 0)
{
TreeNode oTreeNode = new TreeNode();
oTreeNode.Name = iID.ToString();
oTreeNode.Text = String.Format("{0} ({1})", sName, iID);
oTreeView.Nodes.Add(oTreeNode);
}
else
{
if (oParentNodes.Length > 0)
{
foreach (TreeNode oParentTreeNode in oParentNodes)
{
TreeNode oTreeNode = new TreeNode();
oTreeNode.Name = iID.ToString();
oTreeNode.Text = String.Format("{0} ({1})", sName, iID);
oParentTreeNode.Nodes.Add(oTreeNode);
}
}
else
{
Console.WriteLine(" ** Could not find the parent node {0} for child {1} ({2})", iParentID, sName, iID);
}
}
}
}
}
protected override void OnLoad(EventArgs E)
{
base.OnLoad(E);
LoadTreeview("Xml.xml");
}
我对 XML 进行了一些修改,使其看起来像这样 - 本质上,它是相同的:
<?xml version="1.0" encoding="utf-8" ?>
<Processes>
<Process id="0" name="[System Process]" ParentPID="0" />
<Process id="4" name="System" ParentPID="0" />
<!--
<Process id="10" name="MissingNode" ParentPID="0" />
<Process id="1764" name="MissingNode" ParentPID="0" />
-->
<Process id="100" name="MyApp.exe" ParentPID="4" />
<Process id="120" name="avgrsx.exe" ParentPID="10"/>
<Process id="150" name="avgcsrvx.exe" ParentPID="120" />
<Process id="155" name="csrss.exe" ParentPID="100" />
<Process id="170" name="winlogon.exe" ParentPID="100" />
<Process id="180" name="services.exe" ParentPID="170" />
<Process id="200" name="lsass.exe" ParentPID="170" />
<Process id="110" name="svchost.exe" ParentPID="180" />
<Process id="380" name="svchost.exe" ParentPID="200"/>
<Process id="530" name="svchost.exe" ParentPID="1764" />
<Process id="420" name="Avg.exe" ParentPID="110" />
</Processes>
最后,以下节点不会出现,因为 XML 中没有它们的定义:
这些在上面包含的 XML 文件中显示为已注释掉。
希望这是您正在寻找的。
干杯!