【问题标题】:Rexml - pretty print with text inline and child tags indentedRexml - 带有内联文本和缩进的子标签的漂亮打印
【发布时间】:2011-01-19 16:34:47
【问题描述】:

我正在使用 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 标签之间没有多余的线,但这对我来说很好。我把这个问题留在这里,以防其他人偶然发现它。

【问题讨论】:

    标签: ruby pretty-print rexml


    【解决方案1】:

    您需要将 formatter 的 compact 属性设置为 true,但您只能通过先设置一个单独的 formatter 对象,然后使用它来编写而不是调用文档自己的 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,这与我在发布后发现的相同(请参阅我的编辑)。
    • 请注意,如果您想避免较长的文本节点行被换行,您还必须设置formatter.width = &lt;very high number&gt;
    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 2016-11-30
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多