.net - XmlDocument 混合内容 pretty-print 行为背后的基本原理是什么?

标签 .net xml pretty-print

.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/

相关文章:

asp.net - 创建新项目时如何更改 dotnet new 模板的名称?

perl - 如何在普通程序代码中使用 perl 调试器漂亮地打印散列?

python - 在 Python 中使用 ElementTree 从 XML 中提取数据

jquery - 将 HTML 字符串转换为 HTML DOM,而不加载/执行脚本/图像?

php - 使用 php 发送 xml

php - 如何在 PHP 中记录 pretty-print json?

git - 如何处理 git 存储库中广泛的代码格式更改

c# - WPF Popup 作为用 xaml 编写的单独控件

c# - gSOAP 客户端的 WCF 服务

.net - 向 .net core csproj 文件添加依赖项