给定如下的XML字符串:
<some><nested><xml>value</xml></nested></some>
什么是使用 Ruby 格式化内容以便阅读的最佳选项?
<some>
<nested>
<xml>value</xml>
</nested>
</some>
给定如下的XML字符串:
<some><nested><xml>value</xml></nested></some>
<some>
<nested>
<xml>value</xml>
</nested>
</some>
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 )
我刚刚注意到builder有一个indent
选项可以实现这个功能。但请您也发布您的答案,因为并非所有想要实现此功能的人都使用builder。此外,对于您没有创建的XML字符串,可能会有更快的解决方案。