简体   繁体   English

XDocument.Load()错误

[英]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. 我无法在XML文档中加载我的响应。 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? 我究竟做错了什么?

Unlike XmlDocument.Load , XDocument.Load is a static method returning a new XDocument : XmlDocument.Load不同, XDocument.Load是一个返回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. 将流读到最后然后创建一个StringReader似乎毫无意义。 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. 首先创建StreamReader也毫无意义 - 如果XML文档不是 UTF-8,它可能会导致问题。 Better: 更好:

For .NET 4, where there's an XDocument.Load(Stream) overload: 对于.NET 4,其中存在XDocument.Load(Stream)重载:

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

For .NET 3.5, where there isn't: 对于.NET 3.5,没有:

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: 或者,只需让LINQ to XML完成所有工作:

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. 编辑:请注意,编译器错误确实为您提供了足够的信息:它告诉您不能将XDocument.Load称为doc.Load ,而是提供类型名称。 Your next step should have been to consult the documentation, which of course gives examples. 您的下一步应该是查阅文档,当然这也是示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM