HtmlTextWriter的构造函数要求必须传递一个与TextWriter接口兼容的实例。大家可以根据需要选择合适的TextWriter接口实 现类,因为该类的选择将决定最终生成的Html文本的输出方式,例如我想把结果输出到一个TextBox中,于是我就使用了StringWriter类的 实例作为参数传入:
StringWriter sw=new System.IO.StringWriter();
HtmlTextWriter writer=new HtmlTextWriter(sw);
如果要获得结果,只需要使用sw.toString()就可以了。注意,HtmlTextWriter本身不提供输出方法或属性。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
protected override void Render(HtmlTextWriter writer)
{
// Set attributes and values along with attributes and styles
// attribute defined for a <span> element.
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "alert('Hello');");
writer.AddAttribute("CustomAttribute", "CustomAttributeValue");
writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "Red");
writer.AddStyleAttribute("Customstyle", "CustomStyleValue");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
// Create a space and indent the markup inside the
// <span> element.
writer.WriteLine();
writer.Indent++;
writer.Write("Hello");
writer.WriteLine();
// Controls the encoding of markup attributes
// for an <img> element. Simple known values
// do not need encoding.
writer.AddAttribute(HtmlTextWriterAttribute.Alt,
"Encoding, \"Required\"",
true);
writer.AddAttribute("myattribute",
"No "encoding " required",
false);
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
writer.WriteLine();
// Create a non-standard markup element.
writer.RenderBeginTag("MyTag");
writer.Write("Contents of MyTag");
writer.RenderEndTag();
writer.WriteLine();
// Create a manually rendered <img> element
// that contains an alt attribute.
writer.WriteBeginTag("img");
writer.WriteAttribute("alt", "A custom image.");
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteEndTag("img");
writer.WriteLine();
writer.Indent--;
writer.RenderEndTag();
}