Search code examples
c#xmllinqxmlreaderhttpwebresponse

How to set XmlReader with HttpWebResponse


I've been having an issue taking a HttpWebResponse and setting it to an XmlReader, with the examples I've looked up so far I've gotten this:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlReader xmlReader;
if (response != null)
{
    StreamReader sr = new StreamReader(response.GetResponseStream());
    //string st = sr.ReadToEnd().Trim();
    xmlReader = XmlReader.Create(sr);
}

But the problem is that xmlReader does not get filled with the entire response, I get a partial response that isn't even valid XML(no closing tags on some nodes) which causes issues when trying to read from that variable later on.

But if I uncomment the following line for testing:

string str = sr.ReadtoEnd().Trim();

The variable str is filled with the entire XML response, but obviously I need it in a form of a XmlReader so I can run LINQ to XML on it.

My question is, what is the best way to be sure that I get the entire response in the XmlReader object?


Solution

  • While this doesn't solve the actual problem, but may help you reach the goal to be able to use LINQ-to-XML on the XML downloaded.

    Using XmlReader isn't the only way to be able to run LINQ-to-XML. Given that you're able to get full XML in the string variable str, you can then use XElement.Parse() or XDocument.Parse() method to load the string to LINQ-to-XML's XElement or XDocument object :

    .....
    StreamReader sr = new StreamReader(response.GetResponseStream());
    string str = sr.ReadToEnd().Trim();
    XDocument doc = XDocument.Parse(str);
    //at this point you can continue doing necessary LINQ-to-XML operations
    .....