C# HtmlEncoder和HtmlDecoder的Bug以及解决方案

it2026-04-05  7

看到群里的讨论,做一个备份。

1.HttpUtility.HtmlEncode和HtmlDecoder有缺陷,没有处理空格(&nbsp;)、回车(<br/> 、<p>)等元素。不过话说回来,如果能处理,那也太强大了。

  http://blog.csdn.net/wd330260402/article/details/5977989 “使用Reflector 查看 HttpUttility.HtmlEncode 的实现,我们就可以看到,它只考虑的五种情况,空格,回车是没有处理的”

 

2.因为Html是基于XML的,如果使用XmlDocument,它不能处理非正规的html格式,也就是说,它不能容错。

 

3.有网友推荐用HtmlAgilityPack,因为它能容错,而且功能还不少,但根据别的网友测试以及反馈来看,HtmlAgilityPack在HtmlEncoder和HtmlDecoder方面,效果并不好,而且还有Bug。

 

4.最终,网友用了微软自己的方案:Microsoft.mshtml。功能多,性能好,还能容错。据说这个控件是IE用来渲染网页的。

   http://www.cnblogs.com/rupeng/archive/2010/06/26/1765840.html

   添加对Microsoft.mshtml这个程序集的引用,并且修改它的属性,把“嵌入互操作类型”改为False,然后编写如下代码:

1 IHTMLDocument2 doc = new HTMLDocumentClass(); 2 string str_html = "<node>A&nbsp;&nbsp;B<ode>"; 3 doc.write(new object[] { str_html }); 4 doc.close(); 5 6 string str_result = doc.body.innerText; 7 8 str_result为"A B"

 

转载于:https://www.cnblogs.com/xxxteam/archive/2013/03/12/2956237.html

相关资源:PHTML Encoder v4.0
最新回复(0)