【问题标题】:Loading XML file returns System.StackOverflowException加载 XML 文件返回 System.StackOverflowException
【发布时间】:2012-12-03 04:21:57
【问题描述】:

我正在读取一个 XML 文件并在 C# 中为我的TreeView 使用数据。我的程序返回错误

“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++;   
    }
}

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    我运行了您的代码并且没有出现异常,但是我确实在您的代码中发现了一个错误:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多