程序在读取XML时冻结

时间:2013-01-27 14:04:44

标签: c# xml

这是我的代码:

using (StreamReader reader = new StreamReader("test.xml"))
{          
    int prev = ' ';
    List<string> info = new List<string>();
    StringBuilder temp = new StringBuilder();

    for (int c; (c = reader.Read()) != -1; )
    {
        if (prev == '>' && c != '<')
        {
            while (c != '<')
            {
                if (c != ' ' && c != '\n' && c != '\r' && c != '\t') temp.Append((char)c);
                c = reader.Read();
            }

            if (temp.Length > 0)
            {
                info.Add(temp.ToString());
                Console.WriteLine(temp.ToString());
                temp.Clear();
            }
        }
        prev = c;
    }

    foreach (string item in info) Console.WriteLine(item);
}

我试图从XML文件中读取有意义的内容(标签之间的信息)(没有在.NET中实现的方法)。该程序似乎读取数据块并将它们成功放入列表中,但是当它到达文件末尾时,它只是冻结而不执行for语句之后的剩余代码。我必须说它不再循环 - 我试过了,它只是冻结了。

XML文件:

<?xml version="1.0"><student><name>Pesho</name>
<age>21</age><interests count="3"><interest>
Games</instrest><interest>C#</instrest><interest>
Java</instrest></interests></student>

1 个答案:

答案 0 :(得分:2)

看起来最内层的循环while循环可以永远读取流,因为它会读取while (c != '<')(-1) != '<'

请注意,当您在!=int)和-1char)之间使用运算符'<'时,后者会自动转换为int,所以它的确如下:

while (c != 60)