C#实现将HTML转换成纯文本的方法

 更新时间:2020年6月25日 11:28  点击:2094

本文实例讲述了C#实现将HTML转换成纯文本的方法。分享给大家供大家参考。具体如下:

使用方法:

复制代码 代码如下:
HtmlToText convert = new HtmlToText();
textBox2.Text = convert.Convert(textBox1.Text);

C#代码如下:

/// <summary>
/// Converts HTML to plain text.
/// </summary>
class HtmlToText
{
  // Static data tables
  protected static Dictionary<string, string> _tags;
  protected static HashSet<string> _ignoreTags;
  // Instance variables
  protected TextBuilder _text;
  protected string _html;
  protected int _pos;
  // Static constructor (one time only)
  static HtmlToText()
  {
    _tags = new Dictionary<string, string>();
    _tags.Add("address", "\n");
    _tags.Add("blockquote", "\n");
    _tags.Add("div", "\n");
    _tags.Add("dl", "\n");
    _tags.Add("fieldset", "\n");
    _tags.Add("form", "\n");
    _tags.Add("h1", "\n");
    _tags.Add("/h1", "\n");
    _tags.Add("h2", "\n");
    _tags.Add("/h2", "\n");
    _tags.Add("h3", "\n");
    _tags.Add("/h3", "\n");
    _tags.Add("h4", "\n");
    _tags.Add("/h4", "\n");
    _tags.Add("h5", "\n");
    _tags.Add("/h5", "\n");
    _tags.Add("h6", "\n");
    _tags.Add("/h6", "\n");
    _tags.Add("p", "\n");
    _tags.Add("/p", "\n");
    _tags.Add("table", "\n");
    _tags.Add("/table", "\n");
    _tags.Add("ul", "\n");
    _tags.Add("/ul", "\n");
    _tags.Add("ol", "\n");
    _tags.Add("/ol", "\n");
    _tags.Add("/li", "\n");
    _tags.Add("br", "\n");
    _tags.Add("/td", "\t");
    _tags.Add("/tr", "\n");
    _tags.Add("/pre", "\n");
    _ignoreTags = new HashSet<string>();
    _ignoreTags.Add("script");
    _ignoreTags.Add("noscript");
    _ignoreTags.Add("style");
    _ignoreTags.Add("object");
  }
  /// <summary>
  /// Converts the given HTML to plain text and returns the result.
  /// </summary>
  /// <param name="html">HTML to be converted</param>
  /// <returns>Resulting plain text</returns>
  public string Convert(string html)
  {
    // Initialize state variables
    _text = new TextBuilder();
    _html = html;
    _pos = 0;
    // Process input
    while (!EndOfText)
    {
      if (Peek() == '<')
      {
        // HTML tag
        bool selfClosing;
        string tag = ParseTag(out selfClosing);
        // Handle special tag cases
        if (tag == "body")
        {
          // Discard content before <body>
          _text.Clear();
        }
        else if (tag == "/body")
        {
          // Discard content after </body>
          _pos = _html.Length;
        }
        else if (tag == "pre")
        {
          // Enter preformatted mode
          _text.Preformatted = true;
          EatWhitespaceToNextLine();
        }
        else if (tag == "/pre")
        {
          // Exit preformatted mode
          _text.Preformatted = false;
        }
        string value;
        if (_tags.TryGetValue(tag, out value))
          _text.Write(value);
        if (_ignoreTags.Contains(tag))
          EatInnerContent(tag);
      }
      else if (Char.IsWhiteSpace(Peek()))
      {
        // Whitespace (treat all as space)
        _text.Write(_text.Preformatted ? Peek() : ' ');
        MoveAhead();
      }
      else
      {
        // Other text
        _text.Write(Peek());
        MoveAhead();
      }
    }
    // Return result
    return HttpUtility.HtmlDecode(_text.ToString());
  }
  // Eats all characters that are part of the current tag
  // and returns information about that tag
  protected string ParseTag(out bool selfClosing)
  {
    string tag = String.Empty;
    selfClosing = false;
    if (Peek() == '<')
    {
      MoveAhead();
      // Parse tag name
      EatWhitespace();
      int start = _pos;
      if (Peek() == '/')
        MoveAhead();
      while (!EndOfText && !Char.IsWhiteSpace(Peek()) &&
        Peek() != '/' && Peek() != '>')
        MoveAhead();
      tag = _html.Substring(start, _pos - start).ToLower();
      // Parse rest of tag
      while (!EndOfText && Peek() != '>')
      {
        if (Peek() == '"' || Peek() == '\'')
          EatQuotedValue();
        else
        {
          if (Peek() == '/')
            selfClosing = true;
          MoveAhead();
        }
      }
      MoveAhead();
    }
    return tag;
  }
  // Consumes inner content from the current tag
  protected void EatInnerContent(string tag)
  {
    string endTag = "/" + tag;
    while (!EndOfText)
    {
      if (Peek() == '<')
      {
        // Consume a tag
        bool selfClosing;
        if (ParseTag(out selfClosing) == endTag)
          return;
        // Use recursion to consume nested tags
        if (!selfClosing && !tag.StartsWith("/"))
          EatInnerContent(tag);
      }
      else MoveAhead();
    }
  }
  // Returns true if the current position is at the end of
  // the string
  protected bool EndOfText
  {
    get { return (_pos >= _html.Length); }
  }
  // Safely returns the character at the current position
  protected char Peek()
  {
    return (_pos < _html.Length) ? _html[_pos] : (char)0;
  }
  // Safely advances to current position to the next character
  protected void MoveAhead()
  {
    _pos = Math.Min(_pos + 1, _html.Length);
  }
  // Moves the current position to the next non-whitespace
  // character.
  protected void EatWhitespace()
  {
    while (Char.IsWhiteSpace(Peek()))
      MoveAhead();
  }
  // Moves the current position to the next non-whitespace
  // character or the start of the next line, whichever
  // comes first
  protected void EatWhitespaceToNextLine()
  {
    while (Char.IsWhiteSpace(Peek()))
    {
      char c = Peek();
      MoveAhead();
      if (c == '\n')
        break;
    }
  }
  // Moves the current position past a quoted value
  protected void EatQuotedValue()
  {
    char c = Peek();
    if (c == '"' || c == '\'')
    {
      // Opening quote
      MoveAhead();
      // Find end of value
      int start = _pos;
      _pos = _html.IndexOfAny(new char[] { c, '\r', '\n' }, _pos);
      if (_pos < 0)
        _pos = _html.Length;
      else
        MoveAhead();  // Closing quote
    }
  }
  /// <summary>
  /// A StringBuilder class that helps eliminate excess whitespace.
  /// </summary>
  protected class TextBuilder
  {
    private StringBuilder _text;
    private StringBuilder _currLine;
    private int _emptyLines;
    private bool _preformatted;
    // Construction
    public TextBuilder()
    {
      _text = new StringBuilder();
      _currLine = new StringBuilder();
      _emptyLines = 0;
      _preformatted = false;
    }
    /// <summary>
    /// Normally, extra whitespace characters are discarded.
    /// If this property is set to true, they are passed
    /// through unchanged.
    /// </summary>
    public bool Preformatted
    {
      get
      {
        return _preformatted;
      }
      set
      {
        if (value)
        {
          // Clear line buffer if changing to
          // preformatted mode
          if (_currLine.Length > 0)
            FlushCurrLine();
          _emptyLines = 0;
        }
        _preformatted = value;
      }
    }
    /// <summary>
    /// Clears all current text.
    /// </summary>
    public void Clear()
    {
      _text.Length = 0;
      _currLine.Length = 0;
      _emptyLines = 0;
    }
    /// <summary>
    /// Writes the given string to the output buffer.
    /// </summary>
    /// <param name="s"></param>
    public void Write(string s)
    {
      foreach (char c in s)
        Write(c);
    }
    /// <summary>
    /// Writes the given character to the output buffer.
    /// </summary>
    /// <param name="c">Character to write</param>
    public void Write(char c)
    {
      if (_preformatted)
      {
        // Write preformatted character
        _text.Append(c);
      }
      else
      {
        if (c == '\r')
        {
          // Ignore carriage returns. We'll process
          // '\n' if it comes next
        }
        else if (c == '\n')
        {
          // Flush current line
          FlushCurrLine();
        }
        else if (Char.IsWhiteSpace(c))
        {
          // Write single space character
          int len = _currLine.Length;
          if (len == 0 || !Char.IsWhiteSpace(_currLine[len - 1]))
            _currLine.Append(' ');
        }
        else
        {
          // Add character to current line
          _currLine.Append(c);
        }
      }
    }
    // Appends the current line to output buffer
    protected void FlushCurrLine()
    {
      // Get current line
      string line = _currLine.ToString().Trim();
      // Determine if line contains non-space characters
      string tmp = line.Replace("&nbsp;", String.Empty);
      if (tmp.Length == 0)
      {
        // An empty line
        _emptyLines++;
        if (_emptyLines < 2 && _text.Length > 0)
          _text.AppendLine(line);
      }
      else
      {
        // A non-empty line
        _emptyLines = 0;
        _text.AppendLine(line);
      }
      // Reset current line
      _currLine.Length = 0;
    }
    /// <summary>
    /// Returns the current output as a string.
    /// </summary>
    public override string ToString()
    {
      if (_currLine.Length > 0)
        FlushCurrLine();
      return _text.ToString();
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#中list用法实例

    这篇文章主要介绍了C#中list用法,结合实例形式分析了C#中list排序、运算、转换等常见操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25