[Solved] XDocument.Load() Error

I have some code:

WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
using (System.IO.StreamReader sr = 
    new System.IO.StreamReader(response.GetResponseStream()))
{
    System.Xml.Linq.XDocument doc = new System.Xml.Linq.XDocument();
    doc.Load(new System.IO.StringReader(sr.ReadToEnd()));
}

I can’t load my response in my XML document. I get the following error:

Member 'System.XMl.Linq.XDocument.Load(System.IO.TextReader' cannot be accessed 
with an instance reference; qualify it with a type name instead.

This is becoming really frustrating.
What am I doing wrong?

Solution #1:

Unlike XmlDocument.Load, XDocument.Load is a static method returning a new XDocument:

XDocument doc = XDocument.Load(new StringReader(sr.ReadToEnd()));

It seems pretty pointless to read the stream to the end then create a StringReader though. It’s also pointless creating the StreamReader in the first place – and if the XML document isn’t in UTF-8, it could cause problems. Better:

For .NET 4, where there’s an XDocument.Load(Stream) overload:

using (var response = request.GetResponse())
{
    using (var stream = response.GetResponseStream())
    {
        var doc = XDocument.Load(stream);
    }
}

For .NET 3.5, where there isn’t:

using (var response = request.GetResponse())
{
    using (var stream = response.GetResponseStream())
    {
        var doc = XDocument.Load(XmlReader.Create(stream));
    }
}

Or alternatively, just let LINQ to XML do all the work:

XDocument doc = XDocument.Load(url);

EDIT: Note that the compiler error did give you enough information to get you going: it told you that you can’t call XDocument.Load as doc.Load, and to give the type name instead. Your next step should have been to consult the documentation, which of course gives examples.

Respondent: Jon Skeet
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.