rubiii
rubiii

Reputation: 6983

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>

Upvotes: 7

Views: 3697

Answers (2)

rubiii
rubiii

Reputation: 6983

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.

Upvotes: 4

steenslag
steenslag

Reputation: 80085

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 )

Upvotes: 12

Related Questions