Class: Ucenter::Tools::Xml

Inherits:
Base
  • Object
show all
Defined in:
lib/ucenter/tools/xml.rb

Instance Method Summary collapse

Methods inherited from Base

#get, #initialize, #post

Constructor Details

This class inherits a constructor from Ucenter::Tools::Base

Instance Method Details

#parse(body) ⇒ Object



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
# File 'lib/ucenter/tools/xml.rb', line 4

def parse body
  reader = Nokogiri::XML::Reader(body)

  result ||= Hash.new
  vars ||= []

  reader.each do |node|
    if node.name == 'item'
      if vars.include?(node.attributes['id'])
        vars.delete(node.attributes['id'])
      else
        vars << node.attributes['id']
      end
    elsif node.name == '#cdata-section'
      # 只能写出这么渣的代码,求高手调教
      case vars.length
        when 1
          result[vars[0]] = node.value
        when 2
          result[vars[0]] = Hash.new if result[vars[0]].nil?
          result[vars[0]][vars[1]] = node.value
        when 3
          result[vars[0]][vars[1]] = Hash.new if result[vars[0]][vars[1]].nil?
          result[vars[0]][vars[1]][vars[2]] = node.value
        when 4
          result[vars[0]][vars[1]][vars[2]] = Hash.new if result[vars[0]][vars[1]][vars[2]].nil?
          result[vars[0]][vars[1]][vars[2]][vars[3]] = node.value
        when 5
          result[vars[0]][vars[1]][vars[2]][vars[3]] = Hash.new if result[vars[0]][vars[1]][vars[2]][vars[3]].nil?
          result[vars[0]][vars[1]][vars[2]][vars[3]][vars[4]] = node.value
      end
    end
  end
  result
end