6

I am generating an HTML string in a WPF application, and I am outputting it to a multiline textbox. Right now the output is wrapping, but is showing up similar to a paragraph. I would like it to be shown as formatted HTML. It wouldn't even have to be very nice formatting, but at least not show a paragraph of HTML.

How can I accomplish this?

2
  • Here is a .net wrapper for HTML Tidy https://github.com/markbeaton/TidyManaged
    – satnhak
    Apr 15, 2011 at 17:27
  • We need more information on what formatting you want. Do you want rich text formatting like bold and italics? Do you want linebreaks inserted somewhere? If so, where? How many? Does your HTML string have tags in it to begin with?
    – TylerH
    Oct 1, 2021 at 15:32

2 Answers 2

12

If your HTML is well-formed XML, then the XElement.ToString() method will format with indents and newlines:

try
{
    formattedOutput = System.Xml.Linq.XElement.Parse(myHtmlString).ToString();
}
catch
{
    // isn't well-formed xml
}
4
  • It will remove <!DOCTYPE html> from HTML Aug 24, 2018 at 8:57
  • 2
    It crashes on unmatched tags like <input> or <img> Jun 28, 2020 at 14:09
  • 1
    If your HTML is well-formed XML - what are the chances?! Oct 1, 2021 at 7:00
  • 1
    @theonlygusti Well-formed XML would imply you are using XHTML instead which would indicate closing tags like <input /> and <img />.
    – TylerH
    Oct 1, 2021 at 15:29
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.