Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/oa_test/from_jsonxml.rb

Overview

Class Method Summary collapse

Class Method Details

.from_json(str) ⇒ Object



7
8
9
# File 'lib/oa_test/from_jsonxml.rb', line 7

def from_json(str)
  JSON.parse(str)
end

.from_xml(xml, strict = true) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/oa_test/from_jsonxml.rb', line 11

def from_xml(xml, strict=true) 
  begin
    XML.default_load_external_dtd = false
    XML.default_pedantic_parser = strict
    result = XML::Parser.string(xml).parse 
    return { result.root.name.to_s => xml_node_to_hash(result.root)} 
  rescue Exception => e
        # raise your custom exception here
  end
end

.xml_node_to_hash(node) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/oa_test/from_jsonxml.rb', line 22

def xml_node_to_hash(node) 
  # If we are at the root of the document, start the hash 
  if node.element? 
   if node.children? 
      result_hash = {} 

      node.each_child do |child| 
        result = xml_node_to_hash(child) 

        if child.name == "text"
          if !child.next? and !child.prev?
            return result
          end
        elsif result_hash[child.name]
            if result_hash[child.name].is_a?(Object::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

      return result_hash 
    else 
      return nil 
   end 
   else 
    return node.content.to_s 
  end 
end