Skip to content

Instantly share code, notes, and snippets.

@fidel
Created October 3, 2012 07:45
Show Gist options
  • Save fidel/3825648 to your computer and use it in GitHub Desktop.
Save fidel/3825648 to your computer and use it in GitHub Desktop.
Nokogiri::XML .to_hash method
module Nokogiri::XML
class Document
def to_hash
self.root.element? ? self.root.to_hash : {self.root.name => self.root.text}
end
end
class Element
def to_hash
{ self.name => self.collect_attributes }
end
def collect_attributes
main_hash = {}
self.children.each do |child|
next if child.name == 'text'
hash = {}
if child.element? && child.children.length > 1
hash[child.name] = child.collect_attributes
else
hash[child.name] = child.text.strip
end
main_hash.merge!(hash)
end
main_hash
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment