Created
September 29, 2010 01:33
-
-
Save ogijun/602153 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
require 'nokogiri' | |
class Nokogiri::XML::Node | |
def to_hash(selector = 'body > *') | |
hash = [] | |
self.css(selector).each do |node| | |
hash << node.collect_nodes | |
end | |
hash | |
end | |
def collect_nodes | |
{ self.name.to_sym => self.collect_attributes.merge(:children => collect_children) } | |
end | |
def collect_attributes | |
self.attributes.inject({}) { |collected, attr| | |
collected.merge attr[0].to_sym => attr[1].to_s.split(/\s+/) | |
} | |
end | |
def collect_children | |
self.element_children.collect { |child| child.collect_nodes } || [] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment