VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • C#移除HTML标记

  移除一段文字中的HTML标记,以消除其中包含的样式和段落等,最常用的办法可能就是正则表达式了。但是请注意,正则表达式并不能处理所有的HTML文档,所以有时采用一个迭代的方式会更好,如for循环。看下面的代码:

复制代码
using System;
using System.Text.RegularExpressions;

/// <summary>
/// Methods to remove HTML from strings.
/// </summary>
public static class HtmlRemoval
{
    /// <summary>
    /// Remove HTML from string with Regex.
    /// </summary>
    public static string StripTagsRegex(string source)
    {
        return Regex.Replace(source, "<.*?>", string.Empty);
    }

    /// <summary>
    /// Compiled regular expression for performance.
    /// </summary>
    static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

    /// <summary>
    /// Remove HTML from string with compiled Regex.
    /// </summary>
    public static string StripTagsRegexCompiled(string source)
    {
        return _htmlRegex.Replace(source, string.Empty);
    }

    /// <summary>
    /// Remove HTML tags from string using char array.
    /// </summary>
    public static string StripTagsCharArray(string source)
    {
        char[] array = new char[source.Length];
        int arrayIndex = 0;
        bool inside = false;

        for (int i = 0; i < source.Length; i++)
        {
            char let = source[i];
            if (let == '<')
            {
                inside = true;
                continue;
            }
            if (let == '>')
            {
                inside = false;
                continue;
            }
            if (!inside)
            {
                array[arrayIndex] = let;
                arrayIndex++;
            }
        }
        return new string(array, 0, arrayIndex);
    }
}
复制代码

  代码中提供了两种不同的方式来移除给定字符串中的HTML标记,一个是使用正则表达式,一个是使用字符数组在for循环中进行处理。来看一下测试的结果:

复制代码
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        const string html = "<p>There was a <b>.NET</b> programmer " +
            "and he stripped the <i>HTML</i> tags.</p>";

        Console.WriteLine(HtmlRemoval.StripTagsRegex(html));
        Console.WriteLine(HtmlRemoval.StripTagsRegexCompiled(html));
        Console.WriteLine(HtmlRemoval.StripTagsCharArray(html));
    }
}
复制代码

  输出结果如下:

There was a .NET programmer and he stripped the HTML tags.
There was a .NET programmer and he stripped the HTML tags.
There was a .NET programmer and he stripped the HTML tags.

  上述代码中分别调用了HtmlRemoval类中的三个不同的方法,均返回了相同的结果,即去除了给定字符串中的HTML标记。推荐使用第二种方法,即直接引用一个预先定义好的RegexOptions.Compiled的正则表达式对象,它比第一种方法速度更快。但是RegexOptions.Compiled有一些缺点,在某些情况下它的启动时间会增加数十倍。具体的内容可以查看下面这两篇文章:

RegexOption.Compiled

Regex Performance

  通常,正则表达式的执行效率并不是最高的,所以HtmlRemoval类中给定了另一种方法,使用字符数组来处理字符串。测试程序提供了1000个HTML文件,每个HTML文件中有大约8000个字符,所有的文件均通过File.ReadAllText方式进行读取,测试结果显示字符数组的方式执行速度是最快的。

Performance test for HTML removal

HtmlRemoval.StripTagsRegex:         2404 ms
HtmlRemoval.StripTagsRegexCompiled: 1366 ms
HtmlRemoval.StripTagsCharArray:      287 ms [最快]


File length test for HTML removal

File length before:                 8085 chars
HtmlRemoval.StripTagsRegex:         4382 chars
HtmlRemoval.StripTagsRegexCompiled: 4382 chars
HtmlRemoval.StripTagsCharArray:     4382 chars

  所以,使用字符数组来处理大批量的文件时可以节省时间。在字符数组方法中,仅仅只是将非HTML标记的字符添加到数组缓冲区,为了提高效率,它使用字符数组和一个新的字符串构造器来接收字符数组和范围,这个会比使用StringBuilder速度更快。

对于自关闭的HTML标记

  在XHTML中,某些标记并不具有独立的关闭标签,如<br/>,<img/>等。上述代码应该能够正确处理自关闭的HTML标记。下面是一些支持的HTML标记,注意,正则表达式方法可能无法正确处理无效的HTML标记。

Supported tags

<img src="" />
<img src=""/>
<br />
<br/>
< div >
<!-- -->

HTML文档中的注释

  本文给出的代码对移除HTML文档注释中的HTML标记可能会失效。有些时候,注释中可能会包含一些无效的HTML标记,在处理时这些HTML标记不会被完全移除。但是,扫描这些不正确的HTML标记有时可能是必要的。

如何验证

  有许多种方法可以用来验证XHTML,我们可以采用和上面代码相同的方式来进行迭代。一个简单的方法是对'<'和'>'进行计数,从而确定它们是否匹配,或者采用正则表达式进行匹配。这里有一些资源介绍了这些方法:

HTML Brackets: Validation

Validate XHTML

  有许多方法都可以用来去除给定字符串中的HTML标记,它们返回的结果也都是正确的。毫无疑问,采用字符数组进行迭代的效率最高。

 

 出处:https://www.cnblogs.com/jaxu/p/3682042.html


相关教程