XHtmlTextWriter
takes second parameter tabString
. I set it to HtmlTextWriter.DefaultTabString
When we use xhtmlTextWriter.WriteLine()
, it indents the code.
But if we use control.RenderControl(xhtmlTextWriter)
, it performs only one indentation for the root element.
public string Rendering(Control baseControl)
{
using (StringWriter stringWriter = new StringWriter())
using (XhtmlTextWriter htmlWriter = new XhtmlTextWriter(stringWriter,
HtmlTextWriter.DefaultTabString))
{
baseControl.RenderControl(htmlWriter);
return stringWriter.ToString();
}
}
It seems like Control.RenderControl()
is recursively aggregating child nodes in a temporary string and then with a single WriteLine()
, its writing to XHtmlTextWriter
.
Ideally, its suppose to call WriteLine()
for each node, to respect HtmlTextWriter
's second parameter.
Due to this glitch, after rendering (un-indented) markup to string, I need to pass the string to XPathDocument
, and create XPathNavigator
then convert back to string, which does the desired formatting.
public string Rendering(Control baseControl)
{
using (StringWriter stringWriter = new StringWriter())
using (XhtmlTextWriter htmlWriter = new XhtmlTextWriter(stringWriter,
HtmlTextWriter.DefaultTabString))
{
baseControl.RenderControl(htmlWriter);
return UnwantedFormatting(stringWriter.ToString());
}
}
private string UnwantedFormatting(string markup)
{
StringReader sr = new StringReader(markup);
XPathDocument doc;
using (XmlReader xr = XmlReader.Create(sr,
new XmlReaderSettings()
{
ConformanceLevel = ConformanceLevel.Fragment
// for multiple roots
}))
{
doc = new XPathDocument(xr);
}
return doc.CreateNavigator().InnerXml.ToString();
}
Is there a better way to render control to string with indentation without this undesired extra formatting step?