Created
October 3, 2012 07:45
-
-
Save fidel/3825648 to your computer and use it in GitHub Desktop.
Nokogiri::XML .to_hash method
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
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