1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Text.RegularExpressions;  
  11.  
  12. /// <summary>  
  13. /// HtmlExtract 抽取html里面的文本信息  
  14. /// </summary>  
  15. public class HtmlExtract  
  16. {  
  17.       
  18.         #region private attributes  
  19.         private string _strHtml;  
  20.         #endregion  
  21.  
  22.         #region public mehtods  
  23.          public HtmlExtract(string inStrHtml)  
  24.         { _strHtml = inStrHtml;}  
  25.  
  26.         public string ExtractText()  
  27.         {  
  28.             string result = _strHtml;  
  29.             result = RemoveComment(result);  
  30.             result = RemoveScript(result);  
  31.             result = RemoveStyle(result);  
  32.             result = RemoveTags(result);  
  33.             return result.Trim();  
  34.         }  
  35.         #endregion  
  36.  
  37.  
  38.      #region private methods  
  39.        private string RemoveComment(string input)  
  40. {  
  41. string result = input;  
  42. //remove comment  
  43. result = Regex.Replace(result, @"<!--[^-]*-->"string.Empty, RegexOptions.IgnoreCase);  
  44. return result;  
  45. }  
  46.        private string RemoveStyle(string input)  
  47. {  
  48. string result = input;  
  49. //remove all styles  
  50. result = Regex.Replace(result, @"<style[^>]*?>.*?</style>"string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);  
  51. return result;  
  52. }  
  53.        private string RemoveScript(string input)  
  54. {  
  55. string result = input;  
  56. result = Regex.Replace(result, @"<script[^>]*?>.*?</script>"string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);  
  57. result = Regex.Replace(result, @"<noscript[^>]*?>.*?</noscript>"string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);  
  58. return result;  
  59. }  
  60.        private string RemoveTags(string input)  
  61. {  
  62. string result = input;  
  63. result = result.Replace(" "" ");  
  64. result = result.Replace("'""\"");  
  65. result = result.Replace("<""<");  
  66. result = result.Replace(">"">");  
  67. result = result.Replace("&""&");  
  68. result = result.Replace("<br>""\r\n");  
  69. result = Regex.Replace(result, @"<[\s\S]*?>"string.Empty, RegexOptions.IgnoreCase);  
  70. return result;  
  71. }  
  72.      #endregion   
  73. }  
  74.