【问题标题】:convert html to plain text using c#使用 c# 将 html 转换为纯文本
【发布时间】:2022-01-25 12:24:29
【问题描述】:

我使用这种方法将 html 转换为纯文本,但它在这个 html 标签中存在一些错误

方法:

public string HtmlToPlainText(string htmlText)
    {
        //const string tagWhiteSpace = @"(>|$)(\W|\n|\r)+<";//matches one or more (white space or line breaks) between '>' and '<'
        const string stripFormatting = @"<[^>]*(>|$)";//match any character between '<' and '>', even when end tag is missing
        const string lineBreak = @"<(br|BR)\s{0,1}\/{0,1}>";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />
        var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
        var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
        //var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);

        var text = htmlText;
        //Decode html specific characters
        text = System.Net.WebUtility.HtmlDecode(text);
        //Remove tag whitespace / line breaks
        //text = tagWhiteSpaceRegex.Replace(text, "><");
        //Replace < br /> with line breaks
        text = lineBreakRegex.Replace(text, Environment.NewLine);
        //Strip formatting
        text = stripFormattingRegex.Replace(text, string.Empty);
        return text;
    }

这是我的 html 文本

<h3> This is a simple title </h3>
</br>
<p>Lorem ipsum <b> dolor sit </b> amet consectetur, <i>adipisicing elit.</i> </p>

这是我的结果

这是一个简单的标题 Lorem ipsum dolor sit amet consectetur,
减肥精英。

结果应该是

这是一个简单的标题

Lorem ipsum dolor sit amet consectetur, adipisicing elit.

我认为错误来自条带格式。我该如何解决?

【问题讨论】:

标签: c# html .net


【解决方案1】:

解析 HTML 不是一件容易的事(即使是 HTML 的一个子集)。如果 regex 感觉是这个任务的一个很好的解决方案,它实际上并不是那么好。要解析 HTML,您应该使用 ... HTML 解析器。在 C# 中,AngleSharpHTMLAgilityPack 是最常见的解决方案。以下是 AngleSharp 的示例:

using System;
using AngleSharp;
using AngleSharp.Html.Parser;

class MyClass {
    static void Main() {
        //Use the default configuration for AngleSharp
        var config = Configuration.Default;

        //Create a new context for evaluating webpages with the given config
        var context = BrowsingContext.New(config);

        //Source to be parsed
        var source = @"<h3> This is a simple title </h3>
</br>
<p>Lorem ipsum <b> dolor sit </b> amet consectetur, <i>adipisicing elit.</i> </p>
";

        //Create a parser to specify the document to load (here from our fixed string)
        var parser = context.GetService<IHtmlParser>();
        var document = parser.ParseDocument(source);

        //Do something with document like the following
        Console.WriteLine(document.DocumentElement.TextContent);
    }
}

Try it Online

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-09-08
    • 2018-03-17
    相关资源
    最近更新 更多