2012-12-03 33 views
1

我正在阅读XML文件并在C#中使用我的TreeView的数据。我的程序返回一个错误加载XML文件返回System.StackOverflowException

类型“System.StackOverflowException” 发生在System.Windows.Forms.dll中的一个未处理的异常。

为什么?

XML文件

<ListOfTopics> 
    <MainTopic url="index.html" title="Homes"> 
    <SubTopic url="index.html" title="Sub Topic1"/> 
    <SubTopic url="index.html" title="Sub Topic2"/> 
    <SubTopic url="index.html" title="Sub Topic3"/> 
    </MainTopic> 
</ListOfTopics> 

C#代码

public void LoadTopics()  
{ 
    XmlDocument xml = new XmlDocument(); 
    xml.Load("topics.xml"); 
    int i = 0; 

    foreach (XmlElement el in xml.DocumentElement.ChildNodes) 
    {   
     TreeNode node = new TreeNode(); 
     node.ToolTipText = el.GetAttribute("url"); 
     node.Name = el.GetAttribute("title"); 
     node.Text = el.GetAttribute("title"); 
     topicTree.Nodes.Add(node); 

     if (el.HasChildNodes) 
     { 
      foreach (XmlElement es in el.ChildNodes) 
      { 
       TreeNode nodes = new TreeNode(); 
       nodes.ToolTipText = es.GetAttribute("url"); 
       nodes.Name = es.GetAttribute("title"); 
       nodes.Text = es.GetAttribute("title"); 
       topicTree.Nodes[i].Nodes.Add(node); 
      } 

     } 
     i++; 
    } 
} 

回答

1

我跑你的代码,并没有异常,但是我发现在你的代码中的错误:

topicTree.Nodes[i].Nodes.Add(node); 

您正在重新添加父节点,将其更改为:

topicTree.Nodes[i].Nodes.Add(nodes); 
+0

噢谢谢你。我没有注意到:)谢谢.. – Snippet