【问题标题】:XDocument.Load(url) Error: Data at the root level is invalid. Line 1 position 1XDocument.Load(url) 错误:根级别的数据无效。线 1 位置 1
【发布时间】:2016-08-11 17:35:28
【问题描述】:

我正在尝试阅读网页上提供的 xml 文档。假设网址是“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)

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

我需要有关下一步操作的帮助...

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

  1. XML 的编码返回额外的字符(我不知道如何检查)
  2. 网页正在阻止请求。 (我不知道如何解决这个问题)

感谢您的时间和帮助:)

【问题讨论】:

  • 如果您可以下载 xml,检查编码的简单方法(通常对我有用)是在记事本中打开它。单击另存为,当前编码应显示在底部。我敢肯定,这可能不是最好的方法。但你至少可以试试。
  • 尝试stackoverflow.com/questions/17795167/… 检测并删除 BOM
  • 还有另一种选择。您可能没有收到 xml 文档,您可能会收到 500 错误或 401、404 等,在这种情况下您会收到 HTML 响应。你说url上的xml看起来不错,你是怎么检查的?
  • 你需要提供一个minimal reproducible example,真的。如果没有实际的 URL 或 XML,您使用的任何答案都只是在黑暗中刺伤。

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


【解决方案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);
        }

感谢 cmets 和帮助!

【讨论】:

  • 我收到错误:TrustFailure(身份验证或解密失败。)请知道如何解决?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 2018-03-30
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多