Skip to content

Instantly share code, notes, and snippets.

@squarism
Last active December 14, 2015 14:48
Show Gist options
  • Save squarism/5102857 to your computer and use it in GitHub Desktop.
Save squarism/5102857 to your computer and use it in GitHub Desktop.
xml to hash real easy
# how can we quickly get to a Hash object from XML?
# what's the disadvantages? what do we throw away?
# maybe sometimes we want to use nokogiri's xpath and other API methods ...
require 'nori'
parser = Nori.new(
:parser => :nokogiri,
:convert_tags_to => lambda { |tag| tag.snakecase.to_sym }
)
# attributes are gone!
doc = parser.parse '<products><product type="fruit">apple</product></products>'
# => {:products=>{:product=>"apple"}}
# or are they?!
doc[:products][:product].attributes
# => {"type"=>"fruit"}
# nori seems to do some magic beyond what Hash is
# even though it claims the objects are hashes -- crazy!!
doc[:products].class
# => Hash
# what?!
# oh ok, it's a hash of special objects
doc[:products][:product].class
# => Nori::StringWithAttributes
# mystery solved.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment