XDocument.Load(url)错误:根级别的数据无效.第1行位置1



我正在尝试阅读网页上提供的xml文档。假设url为"http://myfirsturl.com".该url中的xml文档似乎不错。

        try
        {
            string url = "http://myfirsturl.com";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            using (XmlReader reader = 
                 XmlReader.Create(new StreamReader(stream))
            {
                var doc = XDocument.Load(reader);
                Console.WriteLine(doc);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

我一直得到以下错误:

   System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
   at System.Xml.Linq.XDocument.Load(XmlReader reader)

我用不同的url尝试了完全相同的代码,例如,它适用于:"http://mysecondurl.com".

我需要帮助下一步该做什么。。。

我已经调查了这个错误,并找到了两个可能的解决方案:

  1. XML的编码返回额外的字符(我不知道如何检查)
  2. 网页正在阻止请求。(我不知道该怎么处理)

感谢您的时间和帮助:)

我所要做的就是将标头设置为接受xml,如下所示:

        try
        {
            string url = "http://myfirsturl.com";
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/xml"; // <== THIS FIXED IT
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    XDocument doc = XDocument.Load(stream);
                    Console.WriteLine(doc);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

感谢您的评论和帮助!

最新更新