what's the best way to format an xml string in ruby?

此生再无相见时 提交于 2019-12-21 12:46:13

问题


given an xml string like this:

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

what's the best option (using ruby) to format it into something readable like:

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

回答1:


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

The #write writes to anything that takes <<(string), so this is valid too:

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



回答2:


just noticed that builder has an indent option to do this. but please post your answers as well. not everyone who wants to do this uses builder. also there may be faster solutions for xml strings that you didn't create yourself.



来源:https://stackoverflow.com/questions/2465911/whats-the-best-way-to-format-an-xml-string-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!