我正在使用 REXML 构建一个 xml 文档,并希望以特定方式输出到文本。该文档是 CuePoint 标签的列表,我使用 Element.new 和 add_element 生成的标签都像这样混合成一行:(stackoverflow 在这里将它们分成两行,但想象以下内容全部在一条线):
<CuePoint><Time>15359</Time><Type>event</Type><Name>inst_50</Name></CuePoint><CuePoint><Time>16359</Time><Type>event</Type><Name>inst_50</Name></CuePoint>
当我将它们保存到文件时,我希望它们看起来像这样:
<CuePoint>
<Time>15359</Time>
<Type>event</Type>
<Name>inst_50</Name>
</CuePoint>
<CuePoint>
<Time>16359</Time>
<Type>event</Type>
<Name>inst_50</Name>
</CuePoint>
我尝试将 .write 函数的值传递为 2,以缩进它们:这会产生以下结果:
xml.write($stdout, 2)
生产
<CuePoint>
<Time>
15359
</Time>
<Type>
event
</Type>
<Name>
inst_50
</Name>
</CuePoint>
<CuePoint>
<Time>
16359
</Time>
<Type>
event
</Type>
<Name>
inst_50
</Name>
</CuePoint>
这是不需要的,因为它在只有文本的标签内容中插入了空格。即名称标签的内容现在是“\n inst_50\n”之类的。这将炸毁读取 xml 的应用程序。
有谁知道我如何按照我想要的方式格式化输出文件?
感谢任何建议,最大
编辑 - 我刚刚通过另一个 StackOverflow 帖子在 ruby-forum 上找到了答案:http ://www.ruby-forum.com/topic/195353
formatter = REXML::Formatters::Pretty.new
formatter.compact = true
File.open(@xml_file,"w"){|file| file.puts formatter.write(xml.root,"")}
这会产生类似的结果
<CuePoint>
<Time>33997</Time>
<Type>event</Type>
<Name>inst_45_off</Name>
</CuePoint>
<CuePoint>
<Time>34080</Time>
<Type>event</Type>
<Name>inst_45</Name>
</CuePoint>
CuePoint 标签之间没有多余的线,但这对我来说很好。我把这个问题留在这里,以防其他人偶然发现它。