【问题标题】:Xdocument.Load(XMLReader.Read()) Is giving me errosXdocument.Load(XMLReader.Read()) 给我错误
【发布时间】:2012-03-26 05:41:39
【问题描述】:

我正在尝试加载文档,请参阅下面的代码

 try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                XmlReader responseReader = XmlReader.Create(response.GetResponseStream());

                XDocument docs = XDocument.Load(responseReader.Read());

上面这行告诉我 xdocument.Load 有一些无效参数。

                //XDocument docs = XDocument.Load(response.GetResponseStream());

此行未加载任何内容 Docs 为空

               XDocument docs = XDocument.Load(responseReader);

这一行没有给出任何重载错误,但什么也不返回。

List<string> books = docs.Descendants("Test")....."Remaining QQuery"

【问题讨论】:

  • 你能贴出实际的错误信息吗?
  • 无法从 Bool 转换为字符串 'system.xml.linq.xdocument.Load(string') 的最佳重载方法匹配有一些无效参数
  • 无需创建XmlReader;你应该能够做到: XDocument docs = XDocument.Load(new StreamReader(response.GetResponseStream()));之后文档是否仍然为空(检查 docs.Nodes.Count)?如果是,是时候查看响应本身了。
  • 这解决了我的问题。非常感谢。
  • @SmilingLily 没问题 - 如果您在响应本身遇到任何问题,我会在下面为您提供更多故障排除提示。令人惊讶的是,一行代码可以解决多少编程问题,不是吗!

标签: asp.net xml linq


【解决方案1】:

改变

XDocument docs = XDocument.Load(responseReader.Read());

XDocument docs = XDocument.Load(responseReader);

XDocument 的方法将接受一个 XmlReader,这就是 responseReader,但是您正在调用 .Read() 方法,该方法仅返回一个布尔值,这就是您收到该错误的原因。

【讨论】:

  • 我之前确实尝试过(在 OP 中提到过),但它没有为文档加载任何内容。即将到来 清空。
【解决方案2】:

首先,您几乎没有 XmlReader;您不能将响应直接加载到 XDocument 中,但是,大多数时候您可以这样做:

XDocument docs = XDocument.Load(new StreamReader(response.GetResponseStream()));

然后检查 docs.Nodes.Count。

如果 docs 仍然是空的,那么是时候查看响应本身了。看看 response.ContentType - 它是什么?

假设响应不是太大,看看吧!你可以这样做:

StreamReader reader = new StreamReader(response.GetResponseSteam()); 字符串文本 = reader.ReadToEnd();

您可以将该字符串转储到任何地方。或者,如果它非常大,您可以将响应保存到磁盘,使用带有响应的 FileStream,或者更简单的 WebClient.DownloadFile(url, path_to_save)

两者都应该足以让你更近一步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2019-01-25
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多