在Ruby中,格式化XML字符串的最佳方法是什么?

7

给定如下的XML字符串:

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

什么是使用 Ruby 格式化内容以便阅读的最佳选项?
<some>
  <nested>
    <xml>value</xml>
  </nested>
</some>
2个回答

12
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 可以写入任何接受 <<(string) 的位置,因此以下代码也是合法的:

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

4

我刚刚注意到builder有一个indent选项可以实现这个功能。但请您也发布您的答案,因为并非所有想要实现此功能的人都使用builder。此外,对于您没有创建的XML字符串,可能会有更快的解决方案。


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