Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beno/284220 to your computer and use it in GitHub Desktop.
Save beno/284220 to your computer and use it in GitHub Desktop.
# 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