.NET XmlDocument 在使用 XmlDocument.Save(TextWriter)
漂亮地打印混合内容节点时有一个有趣的行为。
行为可以概括为“一旦 pretty-print 遇到文本节点,它就会禁用当前子树其余部分的缩进和自动换行”。
这是一个例子(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 会那样工作?
最佳答案
这种行为很不幸,但我认为这可以通过 Formatting.Indented 的描述来解释。 XmlTextWriter 的选项(这是 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作者,答案是它不会直到它真正遇到字符数据。那时,它切换到“混合内容”模式并禁止格式化。不幸的是,撤消已写入基础流的子节点的格式为时已晚。
关于.net - XmlDocument 混合内容 pretty-print 行为背后的基本原理是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28967444/