This is my code:
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);
}
I’m trying to read the meaningful content (the info between tags) from an XML file (without methods implemented in .NET). The program seems to read the data chunks and put them in a list successfully, but when it reaches the end of file it just freezes without executing the remaining code after the for statement. I must say that it isn’t looping anymore – I tried that, it just freezes.
The XML file:
<?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>
It looks like the inner-most loop, the
whileloop, can keep reading from the stream forever becasue it readswhile (c != '<'), and(-1) != '<'.Note that when you use the operator
!=between anint(-1) and achar('<'), the latter is automatically converted toint, so it really reads: