StreamReader and reading an XML file

Badr Hari picture Badr Hari · Jan 30, 2011 · Viewed 62.7k times · Source

I get a response from a web-server using StreamReader... now I want to parse this response (it's an XML document file) to get its values, but every time I try to do it I get a error: Root element is missing.

If I read the same XML file directly, the file is well formatted and I can read it.

This is the stream:

WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();

And this is how I try to read the XML file:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(responseReader);
XmlNodeList address = xmlDoc.GetElementsByTagName("original");

Answer

Marc Gravell picture Marc Gravell · Jan 30, 2011

You have called ReadToEnd(), hence consumed all the data (into a string). This means the reader has nothing more to give. Just: don't do that. Or, do that and use LoadXml(reaponseString).