views:

70

answers:

2

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>
+2  A: 

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.

rubiii
+2  A: 
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 )
steenslag