-
-
Save nathamanath/99dc8822c264cc010f40 to your computer and use it in GitHub Desktop.
Modified to handle tree with node attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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