XHtmlTextWriter
接受第二个参数tabString
。我把它设置为HtmlTextWriter.DefaultTabString
当我们使用xhtmlTextWriter.WriteLine()
时,它会缩进代码。
但是如果我们使用control.RenderControl(xhtmlTextWriter)
,它只会对根元素执行一次缩进。
public string Rendering(Control baseControl)
{
using (StringWriter stringWriter = new StringWriter())
using (XhtmlTextWriter htmlWriter = new XhtmlTextWriter(stringWriter,
HtmlTextWriter.DefaultTabString))
{
baseControl.RenderControl(htmlWriter);
return stringWriter.ToString();
}
}
似乎Control.RenderControl()
是在一个临时字符串中递归地聚合子节点,然后用单个WriteLine()
, 将其写入XHtmlTextWriter
.
理想情况下,它假设调用WriteLine()
每个节点,以尊重HtmlTextWriter
的第二个参数。
由于这个故障,在将(未缩进)标记呈现为字符串后,我需要将字符串传递给XPathDocument
,然后创建XPathNavigator
然后转换回字符串,这会执行所需的格式。
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();
}
有没有更好的方法可以在没有这种不需要的额外格式化步骤的情况下将控件呈现给带有缩进的字符串?