Rexml - 美观打印文本同时缩进子标签

9

我正在使用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标记之间没有额外的空行,但这对我来说没关系。我将保留这个问题,以防其他人遇到同样的情况。

1个回答

18

你需要将格式化程序的紧凑属性设置为true,但你只能通过先设置一个单独的格式化程序对象,然后使用该对象进行写入而不是调用文档自己的write方法来实现。

formatter = REXML::Formatters::Pretty.new(2)
formatter.compact = true # This is the magic line that does what you need!
formatter.write(xml, $stdout)

谢谢dmarkow,这正是我在发布后想到的(请参见我的编辑)。 - Max Williams
3
请注意,如果您想避免文本节点的较长行被换行,还需要设置 formatter.width = <非常大的数字> - Alexander Klimetschek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接