Source

XmlFormatter4JR / xmlformatter.rb

require 'rexml/document'
require 'rexml/formatters/pretty'


=begin
This method to format xml string.

[in_xml]
  Target xml string.
[indent]
  Indentation width.
=end
def format_xml(in_xml, indent=2)
  doc = REXML::Document.new(in_xml)
  if indent > 0
    formatter = REXML::Formatters::Pretty.new(indent)
    formatter.compact = true
  else
    raise "require indent is greater than 0. #{indent} is not greater than 0."
  end
  out_xml = ""
  formatter.write(doc, out_xml)
  return out_xml
end


if __FILE__ == $0
  xml = ""
  ARGF.each do |line| xml += line end

  out_xml = format_xml(xml)
  puts out_xml
end