Need tool to format html (indent, add whitespace)

2019-02-19 21:50发布

问题:

I am working on a .net project that generates html.

When the html string is generated, the is no whitespace or indenting. This makes understanding the generated html difficult.

Is there a tool that will take my string of generated html and format it so that it looks nice?

回答1:

If you're generating the HTML yourself, it should be valid XML.

Therefore, you can use the XDocument class to format it.

You can build the HTML inside an XDocument, then call ToString(), which will automatically format the HTML for you.

In addition, XDocument should be much easier to use than manual string concatenation, and will intrinsically protect you from most (but not all) XSS attacks.



回答2:

Here's an online version of Tidy



回答3:

You might be interested in taking a look at Tidy, http://tidy.sourceforge.net/



回答4:

You could use HTMLTextWriter and call HTMLTextWriter.Indent to set the indention of the lines.



回答5:

using https://github.com/AngleSharp/AngleSharp

var parser = new HtmlParser();
var document = parser.Parse(html);

using (var writer = new StringWriter())
{
    document.ToHtml(writer, new PrettyMarkupFormatter());
    return writer.ToString();
}