`
ihuashao
  • 浏览: 4744945 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Convert HTML to Plain Text (把HTML文本转换成纯文本)

阅读更多

Introduction

This article provides the procedure for stripping out HTML tags while preserving most basic formatting. In other words, it converts HTML to plain text.

Background

This example heavily relies on regular expressions, in particular System.Text.RegularExpressions.Regex.Replace() method. You may also find this reference on regular expressions syntax useful.

Using the Code

The code uses System.Text.RegularExpressions namespace and consists of a single function, StripHTML().

First, the development formatting is removed such as tabs used for step-identations and repeated whitespaces. As a result, the input HTML is "flattened" into one continuous string. This serves two reasons:

  1. To remove the formatting ignored by browsers
  2. To make the regexes work reliably (they seem to get confused by escape characters)

Then the header is removed by removing anything between <head> and </head> tags.

Then, all scripts are removed by chopping out anything between <script> and </script> tags inclusive. Similarly with styles.

Then the basic formatting tags, such as <BR> and <DIV> are replaced with \r or \r\r. Also <TR> tags are replaced by line breaks and <TD>s by tabs.

<LI>s are replaced by *s and special characters such as are replaced with their corresponding values.

Finally all the remaining tags are replaced with empty strings.

By this stage, there are likely to be a lot of redundant repeating line breaks and tabs. Any sequence over 2 line breaks long is replaced by two line breaks. Similarly with tabs: sequences over 4 tabs long are replaced by 4 tabs.

Collapse Copy Code
private string StripHTML(string source)
{
    try
    {
        string result;

        // Remove HTML Development formatting
        // Replace line breaks with space
        // because browsers inserts space
        result = source.Replace("\r", " ");
        // Replace line breaks with space
        // because browsers inserts space
        result = result.Replace("\n", " ");
        // Remove step-formatting
        result = result.Replace("\t", string.Empty);
        // Remove repeating spaces because browsers ignore them
        result = System.Text.RegularExpressions.Regex.Replace(result,
                                                              @"( )+", " ");

        // Remove the header (prepare first by clearing attributes)
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*head([^>])*>","<head>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"(<( )*(/)( )*head( )*>)","</head>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(<head>).*(</head>)",string.Empty,
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // remove all scripts (prepare first by clearing attributes)
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*script([^>])*>","<script>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"(<( )*(/)( )*script( )*>)","</script>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        //result = System.Text.RegularExpressions.Regex.Replace(result,
        //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
        //         string.Empty,
        //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"(<script>).*(</script>)",string.Empty,
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // remove all styles (prepare first by clearing attributes)
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*style([^>])*>","<style>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"(<( )*(/)( )*style( )*>)","</style>",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(<style>).*(</style>)",string.Empty,
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // insert tabs in spaces of <td> tags
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*td([^>])*>","\t",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // insert line breaks in places of <BR> and <LI> tags
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*br( )*>","\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*li( )*>","\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // insert line paragraphs (double line breaks) in place
        // if <P>, <DIV> and <TR> tags
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*div([^>])*>","\r\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*tr([^>])*>","\r\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<( )*p([^>])*>","\r\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // Remove remaining tags like <a>, links, images,
        // comments etc - anything that's enclosed inside < >
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"<[^>]*>",string.Empty,
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // replace special characters:
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @" "," ",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&bull;"," * ",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&lsaquo;","<",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&rsaquo;",">",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&trade;","(tm)",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&frasl;","/",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&lt;","<",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&gt;",">",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&copy;","(c)",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&reg;","(r)",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        // Remove all others. More can be added, see
        // http://hotwired.lycos.com/webmonkey/reference/special_characters/
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 @"&(.{2,6});", string.Empty,
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // for testing
        //System.Text.RegularExpressions.Regex.Replace(result,
        //       this.txtRegex.Text,string.Empty,
        //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        // make line breaking consistent
        result = result.Replace("\n", "\r");

        // Remove extra line breaks and tabs:
        // replace over 2 breaks with 2 and over 4 tabs with 4.
        // Prepare first to remove any whitespaces in between
        // the escaped characters and remove redundant tabs in between line breaks
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\r)( )+(\r)","\r\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\t)( )+(\t)","\t\t",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\t)( )+(\r)","\t\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\r)( )+(\t)","\r\t",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        // Remove redundant tabs
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\r)(\t)+(\r)","\r\r",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        // Remove multiple tabs following a line break with just one tab
        result = System.Text.RegularExpressions.Regex.Replace(result,
                 "(\r)(\t)+","\r\t",
                 System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        // Initial replacement target string for line breaks
        string breaks = "\r\r\r";
        // Initial replacement target string for tabs
        string tabs = "\t\t\t\t\t";
        for (int index=0; index<result.Length; index++)
        {
            result = result.Replace(breaks, "\r\r");
            result = result.Replace(tabs, "\t\t\t\t");
            breaks = breaks + "\r";
            tabs = tabs + "\t";
        }

        // That's it.
        return result;
    }
    catch
    {
        MessageBox.Show("Error");
        return source;
    }
}

Points of Interest

Escape characters such as \n and \r had to be removed first because they cause regexes to cease working as expected.

Moreover, to make the result string display correctly in the textbox, one might need to split it up and set textbox's Lines property instead of assigning to Text property.

Collapse Copy Code
this.txtResult.Lines =
      StripHTML(this.txtSource.Text).Split("\r".ToCharArray());

History

  • 6th October, 2005: Initial post

<!-- Main Page Contents End -->

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

分享到:
评论

相关推荐

    EndNote X9

    EndNote X9 是一款在学术界比较主流的文献管理软件,可以进行文献批量下载和管理、写作论文时添加索引、分析某篇文献的引文索引、分析某领域或者学术课题的经典文献地位等,功能强大。该资源含有安装包 安装破解...

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

    本文实例讲述了C#实现将HTML转换成纯文本的方法。分享给大家供大家参考。具体如下: 使用方法: 代码如下:HtmlToText convert = new HtmlToText(); textBox2.Text = convert.Convert(textBox1.Text); C#代码如下: ...

    【Java】将Markdown格式文本转换为纯文本

    然而,有时我们可能需要将Markdown格式的文本转换为更简单的纯文本格式,以便于处理或展示。在Java环境中,虽然没有像Markdown到HTML转换那样广泛可用的库,但依然有一些方法可以实现这个功能。 首先,我们需要理解...

    文档格式转换 pdf to html

    ```plaintext #-----beginChineseSimplifiedsupportpackage cidToUnicodeAdobe-GB1xpdf-chinese-simplified\Adobe-GB1.cidToUnicode unicodeMapISO-2022-CNxpdf-chinese-simplified\ISO-2022-CN.unicodeMap ...

    Base64加密解密.zip

    Base64是一种常见的数据编码方式,它将二进制数据转化为可打印的ASCII字符,常用于在网络上传输或存储非ASCII字符的数据。在C#编程环境中,Base64的加密和解密操作是非常基础且实用的功能,特别是在处理如图片、证书...

    将RTF转换为纯文本(再次修订)

    标题“将RTF转换为纯文本(再次修订)”指的是一个技术性过程,涉及将Rich Text Format (RTF) 文件转换成普通的纯文本文件。RTF是一种格式化文本的存储格式,广泛用于不同应用程序间的数据交换,因为它可以保存字体...

    Python_转换PDF到markdown快速与高精度.zip

    然后,我们可以利用`pypandoc`将处理后的文本转换为Markdown: ```python import pypandoc def convert_to_markdown(text): return pypandoc.convert_text(text, 'md', format='plain') markdown_text = convert...

    c#中 base64字符串与普通字符串互转

    在C#中,我们可以使用`System.Convert`类的`ToBase64String`方法将普通字符串(UTF-8编码的字节数组)转换为Base64字符串。首先,我们需要将字符串转换为字节数组,然后进行编码。 ```csharp string plainText = ...

    TextToBinary:将txt文件的上下文从文本到二进制转换为另一个文件

    文本到二进制转换版本 1.0 12/28/2014 一般使用说明 这个程序是用 Python 3.3 构建的,与 Python 2.X 不兼容。 必须安装 Python 3.3 或更高版本 程序由命令行使用。 已经过测试可以转换 .txt 和 .md 文件,目前...

    C# 文字转语音 百度

    在IT行业中,文本转语音(Text-to-Speech, TTS)技术是一种广泛应用的功能,它能够将文字信息转化为可听的语音输出。在这个“C# 文字转语音 百度”的项目中,我们将探讨如何利用百度AI的语音合成接口来实现这一功能...

    vb写的base64加解密

    2. **Convert**: `System.Convert`类提供了许多用于数据类型转换的方法,其中包括`ToBase64String()`和`FromBase64String()`。这两个方法分别用于将字节数组编码为Base64字符串和将Base64字符串解码回字节数组。 3....

    Java实现TXT文件转图片

    例如,在创建电子书、海报或是其他类型的媒体时,有时需要将纯文本信息转化为视觉友好的图像形式。本文将详细介绍如何不依赖任何外部JAR包的情况下,仅使用Java标准库中的类来实现这一功能。 #### 技术要点 本项目...

    .NET Base64加密解密实例

    这段代码首先使用`UTF8.GetBytes`方法将字符串转换为字节数组,然后使用`Convert.ToBase64String`将字节数组编码为Base64字符串。 接下来,我们讨论如何解密Base64编码的字符串。解密过程正好相反,它将Base64字符...

    Base64 个性化加密解密功能VB源码

    Dim plainText As String = "这是待加密的文本" Dim plainBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText) Dim base64Text As String = Convert.ToBase64String(plainBytes) ``` 解码过程则相反...

    文件编码批量转换工具,具备编码侦测能力

    MIME类型是互联网上传输的数据类型的一种标准表示,如text/plain(纯文本)、application/pdf(PDF文件)等。这个库可以帮助工具更准确地判断文件的内容,尤其是对于含有多种数据类型的复杂文件,如包含嵌入图片或...

    C# AES 加密算法

    string plainText = "这是一段需要加密的文本"; byte[] key = Encoding.UTF8.GetBytes("这是一把密钥"); // 密钥,必须是16, 24, 或者32字节 byte[] iv = Encoding.UTF8.GetBytes("这是初始化向量"); // 初始化...

    vb字符串加解密

    这个示例展示了如何使用AES解密算法将加密的字符串恢复成原始文本。 三、注意事项 1. 安全密钥管理:密钥是加密和解密的核心,必须妥善保管。如果密钥被泄露,加密数据的安全性将受到威胁。考虑使用密钥派生函数...

    Endnote生成的中英文混排参考文献中.pdf

    通过“Convert Citations and Bibliography”中的“Convert to Plain Text”选项,Endnote会生成一个新的文档,其中的引用和参考文献已转换为非域文本。 接下来,使用Word的查找替换功能进行最后的调整。首先,查找...

    仿QQ在RichTextBox控件加入图片

    你可以使用`MemoryStream`和`BinaryReader`读取图片数据,然后使用`Convert.ToBase64String`方法进行转换。 3. **创建RTF图片标记**:构建RTF图片标记,其结构大致如下: ``` {\pict \pngblip ...base64编码... }...

Global site tag (gtag.js) - Google Analytics