Class: Hash

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_libxml(xml, strict = true) ⇒ Object



98
99
100
101
102
103
104
# File 'lib/libxml_to_hash.rb', line 98

def from_libxml(xml, strict=true) 
  begin
    from_libxml!(xml, strict)
  rescue Exception => e
    nil
  end
end

.from_libxml!(xml, strict = true) ⇒ Object



91
92
93
94
95
96
# File 'lib/libxml_to_hash.rb', line 91

def from_libxml!(xml, strict=true) 
  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)} 
end

.xml_node_to_hash(node) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/libxml_to_hash.rb', line 106

def xml_node_to_hash(node) 
  n = LibXmlNode.new
  if node.element? 
    node.attributes.each do |attribute|
      n.add_attribute attribute.name.to_s, attribute.value
    end

    node.each_child do |child| 
      if child.text?
        if not child.children?
          n.add_text child.content.to_s.strip
        end
      else
        n.add_node child.name.to_s, xml_node_to_hash(child) 
      end
    end
  end 
  return n.simplify
end

Instance Method Details

#iterableObject



86
87
88
# File 'lib/libxml_to_hash.rb', line 86

def iterable
  [self]
end