XDocument.Load(url) Error: Data at the root level is invalid. Line 1 position 1

XDocument.Load(url) Error: Data at the root level is invalid. Line 1 position 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 returns 额外字符的编码(我不知道如何检查)
  2. 该网页正在阻止该请求。 (我不知道如何解决这个问题)

感谢您的宝贵时间和帮助:)

我所要做的就是将 headers 设置为接受 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);
        }

感谢您的评论和帮助!