Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 516
rubiii Avatar asked Mar 17 '10 21:03

rubiii


1 Answers

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 )
like image 58
steenslag Avatar answered Sep 29 '22 09:09

steenslag