Sha256: 0e8e30c414eac4edbd783416e22858c2550f72e5ae089e3535575c57f9f1a7ef

Contents?: true

Size: 1.16 KB

Versions: 5

Compression:

Stored size: 1.16 KB

Contents

module Vacuum
  module Response
    module Utils
      # Builds a Hash from an XML document.
      #
      # xml - a Nokogiri::XML::Document or Nokogiri::XML::Element.
      #
      # Returns a Hash representation of the XML document.
      def self.xml_to_hash(xml)
        case xml
        when Nokogiri::XML::Document
          xml_to_hash xml.root
        when Nokogiri::XML::Element
          hsh = {}

          xml.attributes.each_pair do |key, attribute|
            hsh[key] = attribute.value
          end

          xml.children.each do |child|
            result = xml_to_hash child

            if child.name == 'text'
              if hsh.empty?
                return result
              else
                hsh['__content__'] = result
              end
            elsif hsh[child.name]
              case hsh[child.name]
              when Array
                hsh[child.name] << result
              else
                hsh[child.name] = [hsh[child.name]] << result
              end
            else
              hsh[child.name] = result
            end
          end

          hsh
        else
          xml.content.to_s
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
vacuum-0.2.2 lib/vacuum/response/utils.rb
vacuum-0.2.1 lib/vacuum/response/utils.rb
vacuum-0.2.0 lib/vacuum/response/utils.rb
vacuum-0.2.0.pre.1 lib/vacuum/response/utils.rb
vacuum-0.2.0.pre lib/vacuum/response/utils.rb