Skip to content

Instantly share code, notes, and snippets.

@nathamanath
Forked from hisapy/hash_to_xml_example.rb
Last active August 29, 2015 14:23
Show Gist options
  • Save nathamanath/99dc8822c264cc010f40 to your computer and use it in GitHub Desktop.
Save nathamanath/99dc8822c264cc010f40 to your computer and use it in GitHub Desktop.
Modified to handle tree with node attributes
require 'nokogiri'
tree = {
node_type: 'form',
children: [
{
node_type: 'div',
attrs: {
class: 'awesome'
},
children: [
{
node_type: 'section',
attrs: {
class: 'nested'
}
}
]
}
]
}
def xml_node(node, xml)
node_type = node[:node_type]
attrs = node[:attrs] || {}
children = node[:children] || []
xml.send(node_type, attrs) do
children.each do |child|
xml_node(child, xml)
end
end
end
builder = Nokogiri::XML::Builder.new do |xml|
xml_node tree, xml
end
puts builder.to_xml save_with: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment