Revisions

gist: 132002 Download_button fork
public
Public Clone URL: git://gist.github.com/132002.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
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
module Hpricot
  
  module Hextensions
    
    def hashify(xml_data)
      hsh = {}
      xml_data.each_child do |b|
        key_name = b.name.strip
        
        if key_name.length > 0
          data = Hpricot.XML(b.inner_html)
          data = (data.children && (data.children.length > 1)) ? data.to_hash : b.inner_html.strip
          
          if hsh[key_name] && !hsh[key_name].is_a?(Array)
            hsh[key_name] = [ hsh[key_name] ] # Convert it into an array...
            hsh[key_name] << data
          elsif hsh[key_name] && hsh[key_name].is_a?(Array)
            hsh[key_name] << data
          else
            hsh[key_name] = data
          end
        end
        
      end
      return hsh
    end
    
  end
  
  class Doc
    include Hextensions
    def to_hash
      hashify(self)
    end
  end
  
  class Elem
    include Hextensions
    def to_hash
      hashify(self)
    end
  end
  
end