Module: AmazonProduct::Builder

Defined in:
lib/amazon_product/builder.rb

Class Method Summary collapse

Class Method Details

.from_xml(xml) ⇒ Object

Builds a hash from a Nokogiri XML document.

In earlier versions of Sucker, I was relying on the XML Mini Nokogiri module in Active Support. This method essentially accomplishes the same.

Based on gist.github.com/335286



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/amazon_product/builder.rb', line 10

def self.from_xml(xml)
  case xml
  when Nokogiri::XML::Document
    from_xml(xml.root)
  when Nokogiri::XML::Element
    result_hash = {}

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

    xml.children.each do |child|
      result = from_xml(child)

      if child.name == 'text'
        if result_hash.empty?
          return result
        else
          result_hash['__content__'] = result
        end
      elsif result_hash[child.name]
        if result_hash[child.name].is_a? Array
          result_hash[child.name] << result
        else
          result_hash[child.name] = [result_hash[child.name]] << result
        end
      else
        result_hash[child.name] = result
      end
    end

    result_hash
  else
    xml.content.to_s
  end
end