Skip to content

Instantly share code, notes, and snippets.

@victorpolko
Last active October 2, 2015 14:08
Show Gist options
  • Save victorpolko/8549136749fad82e4405 to your computer and use it in GitHub Desktop.
Save victorpolko/8549136749fad82e4405 to your computer and use it in GitHub Desktop.
Ruby: Parse Nokogiri XML-node to Ruby Hash instance
nokogiri_xml_to_hash = lambda do |node|
out_hash = {}
return out_hash if node.nil?
node.attributes.each { |k,_| out_hash[k] = node.attr(k) }
node.elements.try(:each) do |elem|
prop = nokogiri_xml_to_hash(elem)
if prop.is_a?(Array) && prop.size > 1
out_hash[elem.name] = prop
else
out_hash[elem.name] ||= []
out_hash[elem.name].push(prop)
end
out_hash[elem.name].flatten!
end
return out_hash.values.flatten if out_hash.size < 2
out_hash
end
@victorpolko
Copy link
Author

It can be used as a method of Nokogiri element (not recommended):

module Nokogiri
  module XML
    class Element
      def to_hash
        out_hash = {}

        attributes.each { |k,_| out_hash[k] = attr(k) }

        elements.try(:each) do |elem|
          prop = nokogiri_xml_to_hash(elem)

          if prop.is_a?(Array) && prop.size > 1
            out_hash[elem.name] = prop
          else
            out_hash[elem.name] ||= []
            out_hash[elem.name].push(prop)
          end

          out_hash[elem.name].flatten!
        end

        return out_hash.values.flatten if out_hash.size < 2

        out_hash
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment