-
-
Save beno/284220 to your computer and use it in GitHub Desktop.
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
# Converting Nokogiri parsed XML to_hash | |
# adds "-2", "-3", etc to the key in case of multiple items | |
# only elements | |
module Extensions | |
module Document | |
def to_hash | |
root.to_hash | |
end | |
end | |
module Node | |
def to_hash | |
iterator = lambda do |node, hash_| | |
counter = 1 | |
node.children.each do |child| | |
name = child.name | |
counter += 1 if hash_[name] | |
name += "-#{counter.to_s}" unless counter == 1 | |
if child.child | |
hash_[name] = {} | |
iterator.call(child, hash_[name]) | |
else | |
hash_[name] = child.text | |
end | |
end | |
end | |
hash = {} | |
iterator.call(self, hash) | |
hash | |
end | |
end | |
end | |
Nokogiri::XML::Document.send(:include, Extensions::Document) | |
Nokogiri::XML::Node.send(:include, Extensions::Node) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment