Sha256: dd06a742202021fcc48dc2bee9ec0c22550dd2f6e36cb210c106f7602b6be4ba

Contents?: true

Size: 1.3 KB

Versions: 8

Compression:

Stored size: 1.3 KB

Contents

require "nokogiri"

class DynportTools::XmlFile
  attr_accessor :path
  
  def initialize(path)
    self.path = path.to_s
  end
  
  def nodes_hash
    { key_for_node(doc.root) => parse_node(doc.root) }
  end
  
  def doc
    @doc ||= Nokogiri::XML(File.open(path))
  end
  
  def parse_node(node)
    child_elements = node.children.select { |n| n.is_a?(Nokogiri::XML::Element) }
    value = if child_elements.any?
      flatten_hash(
        child_elements.inject({}) do |hash, el|
          hash[key_for_node(el)] ||= Array.new
          hash[key_for_node(el)] << parse_node(el)
          hash
        end
      )
    else
      txt = node.inner_text.strip
      txt.length == 0 ? nil : txt
    end
  end
  
  def key_for_node(node)
    if node.attributes.any?
      node.attributes.inject({ :name => node.name }) do |hash, (key, value)|
        hash.merge!(key => value.value)
      end
    else
      node.name
    end
  end
  
  def flatten_hash(in_hash)
    in_hash.inject({}) do |hash, (key, arr_of_value)|
      if arr_of_value.is_a?(Array)
        if arr_of_value.length == 0
          hash[key] = nil
        elsif arr_of_value.length == 1
          hash[key] = arr_of_value.first
        else
          hash[key] = arr_of_value
        end
      else
        hash[key] = arr_of_value
      end
      hash
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
dynport_tools-0.2.8 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.6 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.5 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.4 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.3 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.2 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.1 lib/dynport_tools/xml_file.rb
dynport_tools-0.2.0 lib/dynport_tools/xml_file.rb