XDocument.Load(feedUrl)返回"数据在根级别无效。 1号线,位置1"级别、位置、数据、Load

2023-09-06 10:44:38 作者:我知道、我不配

首先,这更是一个解决方案,比的问题。我花了一段时间来解决,所以我想我的决议案可能值得分享的。

first of all, this is more of a solution, than a question. It took me a while to resolve, so I thought my resolution might worth sharing.

我试图加载使用RSS供稿 XDoument.Load(feedUrl)并获得上述的异常。我查了养活自己在我的浏览器和格式看起来很正常。因此,发现了一些之后的类似于的这里的情况:

I was trying to load an RSS feed using XDoument.Load(feedUrl) and was getting the above Exception. I checked the feed itself in my browser and the format looked fine. So after finding some similar situations here:

的含义 - &LT; XML版本=&QUOT; 1.0&QUOT;编码=&QUOT; UTF-8英寸;&GT; Why &QUOT;数据在根级别无效。 1号线,位置1&QUOT;对XML文档? 的LINQ to XML解析RSS订阅 Meaning of - <?xml version="1.0" encoding="utf-8"?> Why "Data at the root level is invalid. Line 1, position 1." for XML Document? LINQ TO XML Parse RSS Feed

和其他地方: 的http://www.i$p$pferjim.com/2014/09/data-at-the-root-level-is-invalid-line-1-position-1/

推荐答案

......我决定它可能不是格式,并且有问题的网站可能会看到该请求作为一个机器人,并提供一个备用的响应。

...I decided it probably wasn't the formatting and that the site in question might be seeing the request as a bot and providing an alternate response.

这是,其实不然!我试图获取饲料与的HttpWebRequest (没有设置用户代理),我刚刚收到 @ 。我试过的与的一个用户代理和我得到的XML我是后。就在那时使用的只是一个案件 XDocument.Parse()

This was, in fact, the case! I tried fetching the feed with an HttpWebRequest (without setting a useragent) and I received just @ . I tried with a useragent and I got the XML I was after. It was then just a case of using XDocument.Parse()

            XDocument doc;

            try
            {
                doc = XDocument.Load(feedUrl);

            }
            catch (XmlException x)
            {
                string xml = Utilities.WebGetRequest(feedUrl);
                doc = XDocument.Parse(xml);

            }
//carry on working with the doc

...

  public static string WebGetRequest(string url)
  {
      try
      {
          HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
          request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
          Stream objStream;
          HttpWebResponse response;
          string retVal;
          StreamReader objReader;
          try
          {
              response = request.GetResponse() as HttpWebResponse;
          }
          catch (WebException ex)
          {
              response = ex.Response as HttpWebResponse;
          }
          objStream = response.GetResponseStream();
          objReader = new StreamReader(objStream);
          retVal = objReader.ReadToEnd();

          objReader.Dispose();
          objStream.Dispose();
          response.Dispose();
          return retVal;
      }
      catch (Exception ex)
      {
          //Log("FeedRequest", url, true, ex);   //log it, display it and move on
          return "";
      }
  }