Error XDocument.Load ()

I have a 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 cannot load my response into 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. 

It becomes really disappointing. What am I doing wrong?

+7
source share
1 answer

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

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

It seems pretty pointless to read the stream to the end and then create a StringReader . It is also pointless to create a StreamReader in the first place - and if the XML document is not in UTF-8, this can cause problems. It's better:

For .NET 4, where there is XDocument.Load(Stream) overload:

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

For .NET 3.5, where not:

 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: Please note that the compiler error provided you with enough information for you: it told you that you cannot call XDocument.Load as doc.Load and instead indicate the type name. The next step was to consult the documentation, which, of course, gives examples.

+13
source

All Articles