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

时间:2016-04-19 13:36:30

标签: c# xml stream linq-to-xml xmlreader

我正在尝试阅读网页上提供的xml文档。假设网址是“http://myfirsturl.com”。该网址上的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)

我尝试使用不同的网址完全相同的代码,例如:“http://mysecondurl.com”。

我需要帮助来了解下一步该做什么......

我已查看错误并找到了解决方案的两个可能方向:

  1. XML的编码会返回额外的字符(我不知道如何检查)
  2. 该网页阻止了该请求。 (我不知道如何解决这个问题)
  3. 感谢您的时间和帮助:)

1 个答案:

答案 0 :(得分:1)

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

感谢您的评论和帮助!