format an xml string in Ruby format an xml string in Ruby ruby ruby

format an xml string in Ruby


What about using nokogiri?

require 'nokogiri'source = '<some><nested><xml>value</xml></nested></some>'doc = Nokogiri::XML sourceputs doc.to_xml# <?xml version=\"1.0\"?>\n<some>\n  <nested>\n    <xml>value</xml>\n  </nested>\n</some>\n


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 possibleformatter.compact = trueformatter.write(doc, $stdout)