开发者

StreamReader and reading an XML file

开发者 https://www.devze.com 2023-02-07 17:55 出处:网络
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:

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");


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).


The Load method is capable of fetching XML documents from remote resources. So you could simplify your code like this:

var xmlDoc = new XmlDocument();
xmlDoc.Load("http://example.com/foo.xml");
var address = xmlDoc.GetElementsByTagName("original");

No need of any WebRequests, WebResponses, StreamReaders, ... (which by the way you didn't properly dispose). If this doesn't work it's probably because the remote XML document is not a real XML document and it is broken.


If you do it with the exact code you pasted in your question, then the problem is that you first read the whole stream into string, and then try to read the stream again when calling xmlDoc.Load(responseReader)

If you have already read the whole stream to the string, use that string to create the xml document xmlDoc.Load(responseString)


Check what's the content of responseString: probably it contains some additional headers that makes the xmlparser unhappy.


The error you are getting means, that XML you receive lacks first element that wraps the whole content. Try wrapping the answer you receive with some element, for example:

   WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXML( "<root>" + responseString + "</root>" );
XmlNodeList address = xmlDoc.GetElementsByTagName("original")

Hope this helped

0

精彩评论

暂无评论...
验证码 换一张
取 消