什么是在ruby中格式化xml字符串的最佳方法?

时间:2010-03-17 21:05:46

标签: xml ruby formatting

给出一个像这样的xml字符串:

<some><nested><xml>value</xml></nested></some>

最好的选择(使用ruby)将其格式化为可读的内容,如:

<some>
  <nested>
    <xml>value</xml>
  </nested>
</some>

2 个答案:

答案 0 :(得分:9)

require "rexml/document"
include REXML

source ='<some><nested><xml>value</xml></nested></some>'
doc = Document.new( source )
doc.write( targetstr = "", 2 ) #indents with 2 spaces
puts targetstr

#write写入任何带&lt;&lt;(字符串)的内容,所以这也是有效的:

doc.write( $stdout, 2 )
doc.write( an_open_file, 2 )

答案 1 :(得分:4)

注意到builderindent选项可以执行此操作。但也请发布你的答案。不是每个想要这样做的人都使用构建器。也可能有更快的解决方案,你没有自己创建的xml字符串。