Quick actions

cmd+k|ctrl+k

Navigation

Languages

hash to xml

Snippet info

Language

Ruby

Visibility

public

Author

hyrious

Created

2020-04-28T04:06:32Z

Updated

2020-04-28T04:06:32Z


require "stringio"
require "rexml/document"

# only support string, array, object, no number
def hash_to_xml a, parent=REXML::Element.new('root')
  case a
  when String
    parent.add_text a
  when Array
    parent, t = parent.parent, parent
    parent.delete_element t
    a.each { |e| hash_to_xml({ t.name => e }, parent) }
  when Hash
    a.each_pair { |k, v|
      k = k.to_s
      if k.start_with? ?-
        parent.add_attribute k[1..-1], v
      else
        e = parent.add_element(k)
        hash_to_xml v, e
      end
    }
  end
  return parent
end

def format_xml(xml)
  StringIO.new.tap { |s|
    REXML::Formatters::Pretty.new.yield_self { |f|
      f.compact = true
      f.write xml, s
    }
  }.string
end

root = {
  '-a': "42", b: { "-c" => ?d },
  es: { e: [{ '-f': "114514", g: { '-h': ?i } }, { j: ?k }] }
}
puts format_xml hash_to_xml root
INFO