You can use the AngleSharp package to accomplish this:
/// <summary>
/// Returns a formatted version of the specified HTML text (which will presumably be unformatted - e.g. all on one line).
/// Uses the AngleSharp library/package.
/// </summary>
public static String FormatHtmlText(String htmlText)
{
try
{
var parser = new AngleSharp.Html.Parser.HtmlParser();
using var document = parser.ParseDocument(htmlText);
using var sw = new StringWriter();
var formatter = new AngleSharp.Html.PrettyMarkupFormatter { Indentation = " ", NewLine = Environment.NewLine };
document.ToHtml(sw, formatter);
return sw.ToString();
}
catch
{
return htmlText;
}
}
The StringWriter
requires a using System.IO;
statement at top.