Skip to content

Instantly share code, notes, and snippets.

@niklas
Created November 18, 2009 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niklas/238278 to your computer and use it in GitHub Desktop.
Save niklas/238278 to your computer and use it in GitHub Desktop.
# works with textnodes, too
Nokogiri::XML::Node.class_eval do
def to_hash
unless children.empty?
h = children.to_hash
if h.length == 1 && h.has_key?(:onlytext)
{ name => h[:onlytext] }
else
{ name => children.to_hash }
end
else
{ name => content }
end
end
end
Nokogiri::XML::NodeSet.class_eval do
def to_hash
inject({}) do |h,c|
h.merge c.to_hash
end
end
end
Nokogiri::XML::Text.class_eval do
def to_hash
c = content.strip
c.blank? ? {} : { :onlytext => content }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment