I'm using an XhtmlTextWriter to write out some Xtml along the following lines:
XhtmlTextWriter writer = // init writer;
writer.WriteLineNoTabs(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AddAttribute("xmlns", "htt开发者_Python百科p://www.w3.org/1999/xhtml");
writer.AddAttribute("xml:lang", "en");
writer.RenderBeginTag(HtmlTextWriterTag.Html);
writer.RenderBeginTag(HtmlTextWriterTag.Head);
writer.RenderBeginTag(HtmlTextWriterTag.Title);
writer.Write("My Title");
writer.RenderEndTag(); // Title
writer.RenderEndTag(); // Head
writer.RenderBeginTag(HtmlTextWriterTag.Body);
writer.RenderBeginTag(HtmlTextWriterTag.H3);
writer.WriteLine("My Heading", userName);
writer.RenderEndTag(); // H3
writer.RenderBeginTag(HtmlTextWriterTag.H6);
writer.WriteLine("My Sub-heading");
writer.RenderEndTag(); // H6
writer.RenderBeginTag(HtmlTextWriterTag.Hr);
writer.RenderEndTag(); // Hr
writer.RenderBeginTag(HtmlTextWriterTag.P);
writer.WriteLine("Hello World.");
writer.RenderEndTag(); // P
writer.RenderEndTag(); // Body
writer.RenderEndTag(); // Html
What I get in the output is something like the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>
My Title
</title>
</head><body>
<h3>
My Heading
</h3><h6>
My Sub-heading
</h6><hr /><p>Hello World.
</p>
</body>
</html>
While this is valid Xhtml I was expecting a newline between tags like </head>
and <body>
. I would make the resulting Xhtml easier to read, for one thing.
Is there a way I can get the XtmlTextWriter to do this?
I messed around a bit with overriding RenderAfterTag
and similar, but since the lack of newline is only in the case of a close tag followed immediately by an open tag it was not immediately obvious how to implement it.
writer.WriteLine()
without args writes a newline character to the output stream
You can extend HtmlTextWriter
which wraps RenderEndTag
and simply writes a new line every time you call it.
public static class extensions {
public static void myRenderEndTag (this HtmlTextWriter writer) {
writer.RenderEndTag();
writer.WriteLine();
}
}
Here it is in action with a usable and abbreviated version of your code:
using (var textWriter = File.CreateText("test.txt"))
using (XhtmlTextWriter writer = new XhtmlTextWriter(textWriter)) {
writer.RenderBeginTag(HtmlTextWriterTag.Html);
writer.RenderBeginTag(HtmlTextWriterTag.Head);
writer.RenderBeginTag(HtmlTextWriterTag.Title);
writer.Write("My Title");
writer.myRenderEndTag(); // Title
writer.myRenderEndTag(); // Head
writer.RenderBeginTag(HtmlTextWriterTag.Body);
writer.myRenderEndTag(); // Body
writer.myRenderEndTag(); // Html
}
精彩评论