Skip to content

Instantly share code, notes, and snippets.

@muja
Last active August 29, 2015 14:08
Show Gist options
  • Save muja/c98d055402b1263a0a7f to your computer and use it in GitHub Desktop.
Save muja/c98d055402b1263a0a7f to your computer and use it in GitHub Desktop.
require 'rexml/document'
module HashToXML
def self.to_xml(any, **options)
document = if any.is_a? REXML::Document
any
else
to_xml_document(any, **options)
end
"".tap do |out|
args = [options["indent"] || 2, options["transitive"], options["ie_hack"]]
document.write(out, *args)
end
end
def self.to_xml_document(any, **options)
document = REXML::Document.new
version = options["version"] || "1.0"
encoding = options["encoding"] || "UTF-8"
document << REXML::XMLDecl.new(version, encoding)
convert(any, document)
document
end
private
def self.convert(any, parent)
case any
when String
parent.text = any
when Hash
any.each do |key, value|
case key
when '__attrs__', '__attributes__'
attributes!(parent, value)
when '__text__'
parent.text = value
else
child = REXML::Element.new(key)
convert(value, child)
parent << child
end
end
when Array
attributes, *children = any
attributes!(parent, attributes)
children.each do |e|
convert(e, parent)
end
else
raise "Unsupported type: #{any.class}!"
end
end
def self.attributes!(element, attrs)
attrs.each { |k, v| element.add_attribute(k, v) }
end
end
### TEST IT:
require 'json'
json = <<JSON
{
"id": "atlassian-theme",
"configuration": {
"file_name": "org.codefirst.SimpleThemeDecorator.xml",
"content": {
"org.codefirst.SimpleThemeDecorator": [
{ "plugin": "[email protected]" },
{
"cssUrl": "http://master.source.test.do/dist/theme.css",
"jsUrl": "http://master.source.test.do/dist/theme.js"
}
]
}
}
}
JSON
h = JSON.parse(json)
content = h["configuration"]["content"]
xml = HashToXML.to_xml(content)
puts xml
# # prints:
# <?xml version='1.0' encoding='UTF-8'?>
# <org.codefirst.SimpleThemeDecorator plugin='[email protected]'>
# <cssUrl>
# http://master.source.test.do/dist/theme.css
# </cssUrl>
# <jsUrl>
# http://master.source.test.do/dist/theme.js
# </jsUrl>
# </org.codefirst.SimpleThemeDecorator>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment