XmlDocument 混合内容漂亮打印行为背后的基本原理是什么?

What is the rationale behind XmlDocument mixed content pretty-printing behavior?

.NET XmlDocument 在使用 XmlDocument.Save(TextWriter).

漂亮打印混合内容节点时有一个有趣的行为

行为可以概括为"once the pretty printer encounters a text node, it disables indentation and automatic newlines for the rest of the current subtree"。

这是一个例子 (http://ideone.com/b1WxD7):

<?xml version='1.0'?>
<root><test><child1/><child2/>foo<child3><child4/></child3></test></root>

印刷精美

<?xml version="1.0"?>
<root>
  <test>
    <child1 />
    <child2 />foo<child3><child4 /></child3></test>
</root>

这种行为似乎不正确也不直观。为什么 XmlDocument 会那样工作?

这种行为很不幸,但我认为这可以通过 XmlTextWriter 的 Formatting.Indented 选项的描述来解释(XmlDocument.Save 在这里使用的选项):

Causes child elements to be indented according to the Indentation and IndentChar settings. This option indents element content only; mixed content is not affected.

此选项的目的是保留 XML 的格式,例如

<p>Here is some <b>bold</b> text.</p>

并且没有将其重新格式化为

<p>
    Here is some 
    <b>
        bold
    </b>
     text.
</p>

但是有一个问题:XmlTextWriter 如何知道元素包含混合内容?因为 XmlTextWriter 是一个 non-cached, forward-only 编写器,答案是它 不会 直到它真正遇到字符数据。那时,它切换到 "mixed content" 模式并禁止格式化。不幸的是,撤消已写入基础流的子节点的格式为时已晚。