Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 readable like :

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

I've found an answer here: what's the best way to format an xml string in ruby?, which is really helpful. But it formats xml like:

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

As my xml string is a little big in length. So it is not readable in this format.

Thanks in advance!

like image 361
mCY Avatar asked Sep 26 '12 09:09

mCY


2 Answers

What about using nokogiri?

require 'nokogiri'
source = '<some><nested><xml>value</xml></nested></some>'
doc = Nokogiri::XML source
puts doc.to_xml
# <?xml version=\"1.0\"?>\n<some>\n  <nested>\n    <xml>value</xml>\n  </nested>\n</some>\n
like image 185
halfelf Avatar answered Oct 30 '22 15:10

halfelf


Use the REXML::Formatters::Pretty formatter:

require "rexml/document" 
source = '<some><nested><xml>value</xml></nested></some>'

doc = REXML::Document.new(source)
formatter = REXML::Formatters::Pretty.new

# Compact uses as little whitespace as possible
formatter.compact = true
formatter.write(doc, $stdout)
like image 30
Sébastien Le Callonnec Avatar answered Oct 30 '22 14:10

Sébastien Le Callonnec