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();
}
有没有更好的方法将控件呈现为带缩进的字符串,而没有这个不需要的额外格式化步骤?