C#移除HTML標記

  移除一段文字中的HTML標記,以消除其中包含的樣式和段落等,最經常使用的辦法可能就是正則表達式了。可是請注意,正則表達式並不能處理全部的HTML文檔,因此有時採用一個迭代的方式會更好,如for循環。看下面的代碼:html

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));
    }
}

  輸出結果以下:express

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.Compiledide

Regex Performance測試

  一般,正則表達式的執行效率並非最高的,因此HtmlRemoval類中給定了另外一種方法,使用字符數組來處理字符串。測試程序提供了1000個HTML文件,每一個HTML文件中有大約8000個字符,全部的文件均經過File.ReadAllText方式進行讀取,測試結果顯示字符數組的方式執行速度是最快的。ui

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速度更快。spa

對於自關閉的HTML標記code

  在XHTML中,某些標記並不具備獨立的關閉標籤,如<br/>,<img/>等。上述代碼應該可以正確處理自關閉的HTML標記。下面是一些支持的HTML標記,注意,正則表達式方法可能沒法正確處理無效的HTML標記。orm

Supported tags

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

HTML文檔中的註釋

  本文給出的代碼對移除HTML文檔註釋中的HTML標記可能會失效。有些時候,註釋中可能會包含一些無效的HTML標記,在處理時這些HTML標記不會被徹底移除。可是,掃描這些不正確的HTML標記有時多是必要的。

如何驗證

  有許多種方法能夠用來驗證XHTML,咱們能夠採用和上面代碼相同的方式來進行迭代。一個簡單的方法是對'<'和'>'進行計數,從而肯定它們是否匹配,或者採用正則表達式進行匹配。這裏有一些資源介紹了這些方法:

HTML Brackets: Validation

Validate XHTML

  有許多方法均可以用來去除給定字符串中的HTML標記,它們返回的結果也都是正確的。毫無疑問,採用字符數組進行迭代的效率最高。

相關文章
相關標籤/搜索