Skip to content

Instantly share code, notes, and snippets.

@mwunsch
Created May 11, 2009 00:37
Show Gist options
  • Save mwunsch/109809 to your computer and use it in GitHub Desktop.
Save mwunsch/109809 to your computer and use it in GitHub Desktop.
Working to build a to_hash method for a Nokogiri::XML::Document
# Converting Nokogiri parsed XML to_hash
require 'nokogiri'
module Extensions
module Document
def to_hash
root.to_hash
end
end
module Node
def to_hash(hash={})
hash[name] = content
walker = lambda do |parent, child, callback|
next if child.blank?
child_hash = {child.name => child.content}
child.children.each { |c| callback.call(child, c, callback) }
end
children.each { |c| walker.call(self, c, walker) }
hash
end
end
end
Nokogiri::XML::Document.send(:include, Extensions::Document)
Nokogiri::XML::Node.send(:include, Extensions::Node)
end
# Probably important:
# http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Node.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment