简体   繁体   English

加载XmlDocument时“解析EntityName时发生错误”

[英]“An error occurred while parsing EntityName” while Loading an XmlDocument

I have written some code to parse RSS feeds for a ASP.NET C# application and it works fine for all RSS feeds that I have tried, until I tried Facebook. 我已经编写了一些代码来解析ASP.NET C#应用程序的RSS提要,并且对于我尝试过的所有RSS提要都可以正常工作,直到尝试了Facebook。

My code fails at the last line below... 我的代码在下面的最后一行失败...

WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream rss = response.GetResponseStream();
XmlDocument xml = new XmlDocument();
xml.Load(rss);

...with the error "An error occurred while parsing EntityName. Line 12, position 53." ...出现错误“解析EntityName时发生错误。第12行,位置53。”

It is hard to work out what is at thhat position of the XML file as the entire file is all in one line, but it is straight from Facebook and all characters appear to be encoded properly except possibly one character (♥). 由于整个文件都在一行中,因此很难弄清楚XML文件的位置,但是它直接来自Facebook,并且所有字符似乎都已正确编码,但可能只有一个字符(♥)。

I don't particularly want to rewrite my RSS parser to use a different method. 我特别不想重写我的RSS解析器以使用其他方法。 Any suggestions for how to bypass this error? 关于如何绕过此错误的任何建议? Is there a way of turning off checking of the file? 有没有办法关闭文件检查?

Look at the downloaded stream. 查看下载的流。 It doesn't contain the RSS feed, but a HTML page with message about incompatible browser. 它不包含RSS提要,而是一个HTML页面,其中包含有关不兼容的浏览器的消息。 That's because when downloading the URL like this, the user agent header is not set. 这是因为在下载这样的URL时,未设置用户代理标头 If you do that, your code should work: 如果这样做,您的代码应该可以工作:

var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "MyApplication";

var xml = new XmlDocument();

using (var response = request.GetResponse())
using (var rss = response.GetResponseStream())
{
    xml.Load(rss);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM