【问题标题】:XDocument.Load() ErrorXDocument.Load() 错误
【发布时间】:2011-10-05 19:45:57
【问题描述】:

我有一些代码:

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.

这变得非常令人沮丧。我做错了什么?

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:

    XmlDocument.Load 不同,XDocument.Load 是一个静态方法返回一个新的XDocument

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

    将流读到最后似乎毫无意义然后创建一个StringReader。首先创建StreamReader 也是没有意义的——如果XML 文档不是 UTF-8,它可能会导致问题。更好:

    对于 .NET 4,存在 XDocument.Load(Stream) 重载:

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

    对于 .NET 3.5,没有:

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

    或者,让 LINQ to XML 完成所有的工作:

    XDocument doc = XDocument.Load(url);
    

    编辑:请注意,编译器错误确实为您提供了足够的信息让您继续前进:它告诉您不能将XDocument.Load 称为doc.Load,而是提供类型名称。您的下一步应该是查阅文档,其中当然提供了示例。

    【讨论】:

    • 执行您推荐的解决方案时,出现错误“无法从 'System.IO.Stream' 转换为 'System.Xml.XmlReader'。
    • 我使用的是 JesseLiberty 的示例,这就是我遇到麻烦的地方。
    • @JoeTyman:XmlReader 是从哪里来的?我没有指定任何需要XmlReader 的内容。该错误来自我的哪个代码示例,来自哪里?
    • @JoeTyman:啊 - XDocument.Load(Stream) 仅在 .NET 3.5 中引入。正在编辑...
    • 我知道这已经过时了,但我不得不说谢谢...... '已经遍历了 MSDN 上的每一寸方法声明,并不太清楚这是一个返回值的函数......
    猜你喜欢
    • 2012-03-26
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2016-08-11
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多