Sha256: 61157aa6051882899a2bbe28ed8da3b2416e77ea45153a7f1b75bc9098c61dd3

Contents?: true

Size: 1.5 KB

Versions: 17

Compression:

Stored size: 1.5 KB

Contents

require 'libxml'

class Hash # :nodoc:
  class << self
        def from_libxml(xml, strict=true)
          begin
            LibXML::XML.default_load_external_dtd = false
            LibXML::XML.default_pedantic_parser = strict
            result = LibXML::XML::Parser.string(xml).parse 
            return { result.root.name.to_s => xml_node_to_hash(result.root)} 
          rescue
            raise $!
            # raise your custom exception here
          end
        end 

        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          
    end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
geocerts-1.0.1 lib/geo_certs/hash_extension.rb
geocerts-1.0.0 lib/geo_certs/hash_extension.rb
geocerts-0.0.25 lib/geo_certs/hash_extension.rb
geocerts-0.0.24 lib/geo_certs/hash_extension.rb
geocerts-0.0.23 lib/geo_certs/hash_extension.rb
geocerts-0.0.22 lib/geo_certs/hash_extension.rb
geocerts-0.0.21 lib/geo_certs/hash_extension.rb
geocerts-0.0.20 lib/geo_certs/hash_extension.rb
geocerts-0.0.19 lib/geo_certs/hash_extension.rb
geocerts-0.0.18 lib/geo_certs/hash_extension.rb
geocerts-0.0.17 lib/geo_certs/hash_extension.rb
geocerts-0.0.16 lib/geo_certs/hash_extension.rb
geocerts-0.0.15 lib/geo_certs/hash_extension.rb
geocerts-0.0.14 lib/geo_certs/hash_extension.rb
geocerts-0.0.13 lib/geo_certs/hash_extension.rb
geocerts-0.0.12 lib/geo_certs/hash_extension.rb
geocerts-0.0.11 lib/geo_certs/hash_extension.rb