Skip to content

Instantly share code, notes, and snippets.

@ueki-kazuki
Created March 4, 2016 08:11
Show Gist options
  • Save ueki-kazuki/973e448f52567b02ade4 to your computer and use it in GitHub Desktop.
Save ueki-kazuki/973e448f52567b02ade4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rexml/document'
require 'json'
file = ARGV[0]
class REXML::Element
def to_h
hash = {}
if self.has_elements?
self.elements.each do |e|
if e.has_elements?
if hash[e.name].nil?
hash[e.name] = e.to_h
elsif hash[e.name].is_a?(Array)
hash[e.name].push( e.to_h )
else
hash[e.name] = [ hash[e.name] ]
hash[e.name].push( e.to_h )
end
elsif e.has_text?
hash[e.name] = e.text
end
end
else
hash[self.name] = self.text
end
hash
end
end
doc = REXML::Document.new open(file).read
obj = doc.root.to_h
puts JSON.dump(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment