我正在使用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>
这是不希望的,因为它在仅包含文本的标签的内容中插入了空格。例如,Name标签的内容现在是“\n inst_50\n ”或其他内容。这将使读取xml的应用程序崩溃。
有人知道我如何按照自己想要的格式格式化输出文件吗?
非常感谢任何建议,Max
编辑-我刚在ruby-forum上找到了答案,通过另一个StackOverflow帖子: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标记之间没有额外的空行,但这对我来说没关系。我将保留这个问题,以防其他人遇到同样的情况。
formatter.width = <非常大的数字>
。 - Alexander Klimetschek