Last active
October 2, 2015 14:08
-
-
Save victorpolko/8549136749fad82e4405 to your computer and use it in GitHub Desktop.
Ruby: Parse Nokogiri XML-node to Ruby Hash instance
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
nokogiri_xml_to_hash = lambda do |node| | |
out_hash = {} | |
return out_hash if node.nil? | |
node.attributes.each { |k,_| out_hash[k] = node.attr(k) } | |
node.elements.try(:each) do |elem| | |
prop = nokogiri_xml_to_hash(elem) | |
if prop.is_a?(Array) && prop.size > 1 | |
out_hash[elem.name] = prop | |
else | |
out_hash[elem.name] ||= [] | |
out_hash[elem.name].push(prop) | |
end | |
out_hash[elem.name].flatten! | |
end | |
return out_hash.values.flatten if out_hash.size < 2 | |
out_hash | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It can be used as a method of Nokogiri element (not recommended):