Skip to content

Instantly share code, notes, and snippets.

@ogijun
Created September 29, 2010 01:33
Show Gist options
  • Save ogijun/602153 to your computer and use it in GitHub Desktop.
Save ogijun/602153 to your computer and use it in GitHub Desktop.
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