XDocument.Load(feedUrl) 返回“根级别的数据无效。第 1 行,位置 1。”

2024-03-11

首先,这更多的是一个解决方案,而不是一个问题。我花了一段时间才解决,所以我认为我的解决方案值得分享。

我试图使用加载 RSS 提要XDoument.Load(feedUrl)并收到上述异常。我检查了养活自己 http://www.limun.hr/rss2.aspx?id=34在我的浏览器中,格式看起来不错。所以在找到一些之后similar这里的情况:

  • - 的含义 https://stackoverflow.com/questions/13743250/meaning-of-xml-version-1-0-encoding-utf-8
  • 为什么“根级别的数据无效。第 1 行,位置 1。”用于 XML 文档? https://stackoverflow.com/questions/17947238/why-data-at-the-root-level-is-invalid-line-1-position-1-for-xml-document/24513288#24513288
  • LINQ TO XML 解析 RSS 源 https://stackoverflow.com/questions/5889954/linq-to-xml-parse-rss-feed

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


...我认为这可能不是格式问题,并且相关网站可能会将请求视为机器人并提供替代响应。

事实确实如此!我尝试用一​​个来获取提要HttpWebRequest(没有设置用户代理)我收到了@。我试过with一个用户代理,我得到了我想要的 XML。这只是一个使用的情况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 "";
      }
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XDocument.Load(feedUrl) 返回“根级别的数据无效。第 1 行,位置 1。” 的相关文章

随机推荐