XhtmlTextWriter Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Writes Extensible Hypertext Markup Language (XHTML)-specific characters, including all variations of XHTML modules that derive from XHTML, to the output stream for an ASP.NET server control for mobile devices. Override the XhtmlTextWriter class to provide custom XHTML rendering for ASP.NET pages and server controls.
public ref class XhtmlTextWriter : System::Web::UI::HtmlTextWriter
public class XhtmlTextWriter : System.Web.UI.HtmlTextWriter
type XhtmlTextWriter = class
inherit HtmlTextWriter
Public Class XhtmlTextWriter
Inherits HtmlTextWriter
- Inheritance
Examples
The code example in this section contains four parts. The first example demonstrates how to create a derived class. The second code example demonstrates how to create a custom control. The third code example demonstrates how to use the custom control. The fourth code example provides the code that is required to run the custom control.
The following code example demonstrates how to create a custom class that is derived from the XhtmlTextWriter class. It has two constructors, which is standard for all classes that inherit directly or indirectly from the HtmlTextWriter class. The first constructor takes a TextWriter object as a parameter and calls the second constructor, passing the following two parameter values:
The TextWriter instance.
The value of the HtmlTextWriter.DefaultTabString property, which defines the default line indentation that is used by the XHTML text writer.
This code example also shows how to override the OnAttributeRender and OnStyleAttributeRender methods to filter for text size and color style, respectively. Additionally, it overrides the BeginRender and EndRender methods to write a text string before and after a control has rendered.
using System;
using System.IO;
using System.Web;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls.Adapters;
namespace Samples.AspNet.CS
{
// Create a class that inherits from XhtmlTextWriter.
[AspNetHostingPermission(SecurityAction.Demand,
Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level=AspNetHostingPermissionLevel.Minimal)]
public class CustomXhtmlTextWriter : XhtmlTextWriter
{
// Create two constructors, following
// the pattern for implementing a
// TextWriter constructor.
public CustomXhtmlTextWriter(TextWriter writer) :
this(writer, DefaultTabString)
{
}
public CustomXhtmlTextWriter(TextWriter writer, string tabString) :
base(writer, tabString)
{
}
// Override the OnAttributeRender method to
// allow this text writer to render only eight-point
// text size.
protected override bool OnAttributeRender(string name,
string value,
HtmlTextWriterAttribute key)
{
if (key == HtmlTextWriterAttribute.Size)
{
if (String.Compare(value, "8pt") == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return base.OnAttributeRender(name, value, key);
}
}
// Override the OnStyleAttributeRender
// method to prevent this text writer
// from rendering purple text.
protected override bool OnStyleAttributeRender(string name,
string value,
HtmlTextWriterStyle key)
{
if (key == HtmlTextWriterStyle.Color)
{
if (String.Compare(value, "purple") == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return base.OnStyleAttributeRender(name, value, key);
}
}
// Override the BeginRender method to write a
// message and call the WriteBreak method
// before a control is rendered.
override public void BeginRender()
{
this.Write("A control is about to render.");
this.WriteBreak();
}
// Override the EndRender method to
// write a string immediately after
// a control has rendered.
override public void EndRender()
{
this.Write("A control just rendered.");
}
}
}
Imports System.IO
Imports System.Web
Imports System.Security.Permissions
Imports System.Web.UI
Imports System.Web.UI.Adapters
Imports System.Web.UI.WebControls.Adapters
Namespace Samples.AspNet.VB
' Create a class that inherits from XhtmlTextWriter.
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class CustomXhtmlTextWriter
Inherits XhtmlTextWriter
' Create two constructors, following
' the pattern for implementing a
' TextWriter constructor.
Public Sub New(writer As TextWriter)
MyClass.New(writer, DefaultTabString)
End Sub
Public Sub New(writer As TextWriter, tabString As String)
MyBase.New(writer, tabString)
End Sub
' Override the OnAttributeRender method to
' allow this text writer to render only eight-point
' text size.
Overrides Protected Function OnAttributeRender(ByVal name As String, _
ByVal value As String, _
ByVal key As HtmlTextWriterAttribute _
) As Boolean
If key = HtmlTextWriterAttribute.Size Then
If String.Compare(value, "8pt") = 0 Then
Return True
Else
Return False
End If
Else
Return MyBase.OnAttributeRender(name, value, key)
End If
End Function
' Override the OnStyleAttributeRender
' method to prevent this text writer
' from rendering purple text.
Overrides Protected Function OnStyleAttributeRender(ByVal name As String, _
ByVal value As String, _
ByVal key As HtmlTextWriterStyle _
) As Boolean
If key = HtmlTextWriterStyle.Color Then
If String.Compare(value, "purple") = 0 Then
Return False
Else
Return True
End If
Else
Return MyBase.OnStyleAttributeRender(name, value, key)
End If
End Function
' Override the BeginRender method to write a
' message and call the WriteBreak method
' before a control is rendered.
Overrides Public Sub BeginRender()
Me.Write("A control is about to render.")
Me.WriteBreak()
End Sub
' Override the EndRender method to
' write a string immediately after
' a control has rendered.
Overrides Public Sub EndRender()
Me.Write("A control just rendered.")
End Sub
End Class
End Namespace
The following code example demonstrates how to create a custom Label control named TestLabel and a custom adapter named XhtmlTestLabelAdapter that renders the content of the control as XHTML.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;
namespace AspNet.Samples
{
// Create a simple class that inherits
// from the Label class.
public class TestLabel : Label
{
private String _textValue;
// Override the Text property.
public override string Text
{
get
{
return (string)ViewState["Text"];
}
set
{
ViewState["Text"] = value;
}
}
}
public class XhtmlTestLabelAdapter : WebControlAdapter
{
// Create a control property that accesses the
// methods and properties of the control.
protected TestLabel Control
{
get
{
return (TestLabel)base.Control;
}
}
protected override void Render(HtmlTextWriter writer)
{
// Create an instance of the XhtmlTextWriter class,
// named w, and cast the HtmlTextWriter passed
// in the writer parameter to w.
XhtmlTextWriter w = new XhtmlTextWriter(writer);
// Create a string variable, named value, to hold
// the control's Text property value.
String value = Control.Text;
// Create a Boolean variable, named attTest,
// to test whether the Style attribute is
// valid in the page that the control is
// rendered to.
Boolean attTest = w.IsValidFormAttribute("style");
// Check whether attTest is true or false.
// If true, a style is applied to the XHTML
// content. If false, no style is applied.
if (attTest)
w.EnterStyle(Control.ControlStyle);
// Write the Text property value of the control,
// a <br> element, and a string. Consider encoding the value using WriteEncodedText.
w.Write(value);
w.WriteBreak();
w.Write("This control conditionally rendered its styles for XHTML.");
// Check whether attTest is true or false.
// If true, the XHTML style is closed.
// If false, nothing is rendered.
if (attTest)
w.ExitStyle(Control.ControlStyle);
}
}
}
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Adapters
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.Adapters
Namespace AspNet.Samples
' Create a simple class that inherits
' from the Label class.
Public Class TestLabel
Inherits Label
Private textValue As String
' Override the Text property.
Overrides Public Property Text As String
Get
Return CStr(ViewState("Text"))
End Get
Set
ViewState("Text") = Value
End Set
End Property
End Class
' Create a class to render the custom Label's
' content to XHTML devices.
Public Class XhtmlTestLabelAdapter
Inherits WebControlAdapter
' Create a Control property that accesses the
' methods and properties of the control.
Protected Shadows ReadOnly Property Control() As TestLabel
Get
Return CType(MyBase.Control, TestLabel)
End Get
End Property
' Override the Render method.
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
' Create an instance of the XhtmlTextWriter class,
' named w, and cast the HtmlTextWriter passed
' in the writer parameter to w.
Dim w As XhtmlTextWriter = New XhtmlTextWriter(writer)
' Create a string variable, named value, to hold
' the control's Text property value.
Dim value As String = Control.Text
' Create a Boolean variable, named attTest,
' to test whether the Style attribute is
' valid in the page that the control is
' rendered to.
Dim attTest As Boolean = w.IsValidFormAttribute("style")
' Check whether attTest is true or false.
' If true, a style is applied to the XHTML
' content. If false, no style is applied.
If (attTest = True) Then
w.EnterStyle(Control.ControlStyle)
End If
' Write the Text property value of the control,
' a <br> element, and a string. Consider encoding the value using WriteEncodedText.
w.Write(value)
w.WriteBreak()
w.Write("This control conditionally rendered its styles for XHTML.")
' Check whether attTest is true or false.
' If true, the XHTML style is closed.
' If false, nothing is rendered.
If (attTest = True) Then
w.ExitStyle(Control.ControlStyle)
End If
End Sub
End Class
End Namespace
The following code example demonstrates how to use the custom control TestLabel on an ASP.NET Web page.
<%@ Page Language="C#" %>
<%@ Import Namespace="AspNet.Samples" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
TestLabel tl = new TestLabel();
tl.ID = "TestLabel1";
PlaceHolder1.Controls.Add(tl);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>XHtmlTextWriter Example</title>
</head>
<body>
<form id="form1" runat="server" >
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="AspNet.Samples" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim tl As TestLabel = New TestLabel()
tl.ID = "TestLabel1"
PlaceHolder1.Controls.Add(tl)
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>XHtmlTextWriter Example</title>
</head>
<body>
<form id="form1" runat="server" >
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
To use the custom control in the preceding code example, add the following <controlAdapters> element to one of two files. You can add it to the appropriate machine-wide file in the subdirectory for a specific browser, as a subfolder of the .NET Framework configuration directory. Alternatively, you can add it to a custom browser file in the App_Browsers directory under the Web application root.
<controlAdapters>
<adapter controlType="AspNet.Samples.TestLabel"
adapterType="AspNet.Samples.XhtmlTestLabelAdapter" />
</controlAdapters>
Remarks
XHTML is an XML-compliant markup language, based on HTML 4.1, which allows you to create Web sites that are suitable for multiple device types. It merges the ease of use provided by HTML with the strict element guidelines provided by XML to produce a markup language with a wide range of format and style options, and with reduced markup tag ambiguity. The XhtmlTextWriter class provides formatting capabilities that ASP.NET server controls use when rendering XHTML content to clients. You can use the SetDocType method to specify which type of XHTML the text writer renders. Supported document types are defined in the XhtmlMobileDocType enumeration.
The XhtmlTextWriter class renders two sets of attributes for elements. One set is a collection of common attributes, as referenced in the CommonAttributes property. The second set is a collection of element-specific attributes, as referenced in the ElementSpecificAttributes property. For more information on the elements and styles that are rendered, see the XHTML modularization specification at the World Wide Web Consortium (W3C) Web site.
You can use the members of the XhtmlTextWriter class and any derived classes to create custom text writers to use in custom XHTML page adapters or class adapters. You can also create derived classes that override the standard behavior of the XhtmlTextWriter class.
By default, when you are working with browsers that support HTML 4.0, ASP.NET pages and controls render markup that is compatible with the XHTML 1.1 standard. For more information, see XHTML Standards in Visual Studio and ASP.NET.
The HtmlTextWriter outputs XHTML unless you configure ASP.NET specifically to not render XHTML markup. For more information, see How to: Configure XHTML Rendering in ASP.NET Web Sites.
Constructors
| Name | Description |
|---|---|
| XhtmlTextWriter(TextWriter, String) |
Initializes a new instance of the XhtmlTextWriter class with the specified line indentation. |
| XhtmlTextWriter(TextWriter) |
Initializes a new instance of the XhtmlTextWriter class that uses the line indentation that is specified in the DefaultTabString field. Use the XhtmlTextWriter(TextWriter) constructor if you do not want to change the default line indentation. |
Fields
| Name | Description |
|---|---|
| CoreNewLine |
Stores the newline characters used for this |
| DefaultTabString |
Represents a single tab character. (Inherited from HtmlTextWriter) |
| DoubleQuoteChar |
Represents the quotation mark (") character. (Inherited from HtmlTextWriter) |
| EndTagLeftChars |
Represents the left angle bracket and slash mark (</) of the closing tag of a markup element. (Inherited from HtmlTextWriter) |
| EqualsChar |
Represents the equal sign ( |
| EqualsDoubleQuoteString |
Represents an equal sign (=) and a double quotation mark (") together in a string (="). (Inherited from HtmlTextWriter) |
| SelfClosingChars |
Represents a space and the self-closing slash mark (/) of a markup tag. (Inherited from HtmlTextWriter) |
| SelfClosingTagEnd |
Represents the closing slash mark and right angle bracket (/>) of a self-closing markup element. (Inherited from HtmlTextWriter) |
| SemicolonChar |
Represents the semicolon (;). (Inherited from HtmlTextWriter) |
| SingleQuoteChar |
Represents an apostrophe ('). (Inherited from HtmlTextWriter) |
| SlashChar |
Represents the slash mark (/). (Inherited from HtmlTextWriter) |
| SpaceChar |
Represents a space ( ) character. (Inherited from |