XDocument.Load() 错误
我有一些代码:
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()));
}
我无法在 XML 文档中加载我的响应。我收到以下错误:
Member 'System.XMl.Linq.XDocument.Load(System.IO.TextReader' cannot be accessed
with an instance reference; qualify it with a type name instead.
这变得非常令人沮丧。我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与
XmlDocument.Load
不同,XDocument.Load
是静态方法返回一个新的XDocument
:将流读到底然后创建一个
StringReader
似乎毫无意义。首先创建StreamReader
也是毫无意义的 - 如果 XML 文档不是采用 UTF-8 格式,则可能会导致问题。更好:对于 .NET 4,有
XDocument.Load(Stream)
重载:对于 .NET 3.5,没有重载:
或者,只需让 LINQ to XML 完成所有 /em> 工作:
编辑:请注意,编译器错误确实为您提供了足够的信息来帮助您继续:它告诉您不能将
XDocument.Load
调用为doc.Load
,并给出类型名称。您的下一步应该是查阅文档,其中当然提供了示例。Unlike
XmlDocument.Load
,XDocument.Load
is a static method returning a newXDocument
:It seems pretty pointless to read the stream to the end then create a
StringReader
though. It's also pointless creating theStreamReader
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:For .NET 3.5, where there isn't:
Or alternatively, just let LINQ to XML do all the work:
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
asdoc.Load
, and to give the type name instead. Your next step should have been to consult the documentation, which of course gives examples.