[英]convert html to plain text using c#
我使用此方法将 html 转换为纯文本,但在此 html 标签 <H1,2,3,..> 中有一些错误
方法:
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 坐在 amet consectetur,adipisicing 精英。
我认为错误来自条带格式。 我该如何解决?
解析 HTML 并非易事(即使对于 HTML 的子集)。 如果 regex 感觉是这个任务的一个很好的解决方案,它实际上并不是那么好。 要解析 HTML,您应该使用... HTML 解析器。 在 C# 中, AngleSharp
和HTMLAgilityPack
是最常见的解决方案。 以下是 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.