【问题标题】:How to convert HTML to plain text [duplicate]如何将 HTML 转换为纯文本 [重复]
【发布时间】:2014-09-24 09:18:19
【问题描述】:

我尝试使用以下函数将 html 转换为纯文本,但在转换时仍然出错。

private static string HtmlToPlainText(string html)
        {
            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 = html;
            //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);
            text = text.Replace(">", "");

            return text;
        }

当我尝试调试代码时,它也会在纯文本输出中显示 \r 和 \r\n。此函数未正确将 html 转换为纯文本。 谁能建议我任何其他转换功能?

谢谢

【问题讨论】:

    标签: c# html plaintext data-conversion


    【解决方案1】:

    可以使用HtmlAgilityPack的HtmlToText demo,可以是found here

    我查看了其他答案,但它们都提出了涉及正则表达式的各种解决方案。我以为HtmlAgilityPack 没有得到足够的关注。

    您只需将NuGet package 插入您的项目并按照示例进行操作即可。

    【讨论】:

    • 不值得使用。它不能正确处理空格。
    • @JitendraPancholi:不确定您尝试了什么,但通常在文档上设置OptionWriteEmptyNodes = true,尤其是在输出为文本时,效果很好。
    • 如何使用这个选项?提供示例代码将是可观的。
    • CodePlex 已不复存在,我相信这个新链接指向 github 中的同一个演示:link
    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 2010-09-22
    • 2015-01-03
    • 2017-03-20
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多