Outside of benefiting from Adaptive Rendering for alternate devices, does it ever make sense to write all of this code:
writer.WriteBeginTag("table");
writer.WriteBeginTag("tr");
writer.WriteBeginTag("td");
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteEncodedText(someTextVariable);
writer.WriteEndTag("td");
writer.WriteEndTag("tr");
writer.WriteEndTag("table");
When StringBuilder could build the same thing with simply this:
sb.Append("<table><tr><td>");
sb.Append(someTextVariable);
sb.Append("</td></tr></table>");
Another advantage could be that using HtmlTextWriter one could format code in a cleaner (more maintenance friendly) way, and that HtmlTextWriter supports encoding HTML automatically. Compare:
writer.AddAttribute(HtmlTextWriterAttribute.Id, "someId");
if (!string.IsNullOrEmpty(cssClass)) writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClass);
writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "Red");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.WriteEncodedText(text);
writer.RenderEndTag();
versus:
StringBuilder html = new StringBuilder();
html.Append("<span");
html.Append(" id=\"someId\"");
if (!string.IsNullOrEmpty(cssClass)) html.AppendFormat(" class=\"{0}\"", HttpUtility.HtmlAttributeEncode(cssClass));
html.Append(">");
html.Append(HttpUtility.HtmlEncode(text));
html.Append("</span>");
One may argue that the code in the second example can be written in a different, possibly cleaner, way, but this could be seen as an advantage of HtmlTextWriter because it basically enforces one canonical way of formatting (which again improves maintenance).
Edit: In fact, I actually made a mistake in the second snippet, and I needed to go back and fix the response. This confirms the point I wanted to make.
I can think of two reasons to use HtmlTextWriter:
You can use the writer to keep track of your indents, so that your outputted HTML is formatted nicely, rather than appearing on one line
HtmlTextWriter is usually associated with an output stream, so it should be more efficient than building up a long string in memory (depending upon how much HTML you are generating).
Neither of these are extraordinary reasons, but they are enough to convince me to use the writer when efficiency is needed, or if I am writing a base control that will be reused and should be as professional as possible. Your mileage may vary :-).
HtmlTextWriter is beneficial because:
HtmlTextWriter is the cleanest and the mark-up is nicely indented when it is rendered.
There is a performance impact as HtmlTextWriter writes directly to the output stream. Stringbuilder doesn't write to the output stream until ToString is called on it.
There is an example on why you would use HtmlTextWriter for Saving and Reusing HTML Output here as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With