Sha256: 322fbf8a67f5f9250d452f145805c15bbd4c843e38466d517b084de9ea299f03

Contents?: true

Size: 1.37 KB

Versions: 31

Compression:

Stored size: 1.37 KB

Contents

module Krikri
  ##
  # An XmlParser
  # @see Krikri::Parser
  class XmlParser < Krikri::Parser
    def initialize(record, root_path = '/')
      xml = Nokogiri::XML(record.to_s)
      ns = namespaces_from_xml(xml)
      @root = Value.new(xml.at_xpath(root_path, ns), ns)
      super(record)
    end

    private

    def namespaces_from_xml(xml)
      namespaces = xml.collect_namespaces.map do |k, v|
        [k.gsub('xmlns:', ''), v]
      end
      namespaces.to_h
    end

    ##
    # An XML Parser Value node class
    # @see Krikri::Parser::Value
    class Value < Krikri::Parser::Value
      def initialize(node, namespaces)
        node = node.root if node.xml?
        @node = node
        @namespaces = namespaces
      end

      delegate :attributes, :xpath, :at_xpath, :css, :at_css, :to => :@node

      def children
        @node.element_children.map do |child|
          return child.name unless child.namespace
          "#{@namespaces.key(child.namespace.href)}:#{child.name}"
        end
      end

      def values
        select_values.map(&:text)
      end

      def values?
        !select_values.empty?
      end

      private

      def get_child_nodes(name)
        @node.xpath("#{@node.path}/#{name}", @namespaces)
          .map { |node| self.class.new(node, @namespaces) }
      end

      def select_values
        @node.children.select(&:text?)
      end
    end
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
krikri-0.13.2 lib/krikri/parsers/xml_parser.rb~
krikri-0.13.1 lib/krikri/parsers/xml_parser.rb~
krikri-0.13.0 lib/krikri/parsers/xml_parser.rb~
krikri-0.12.4 lib/krikri/parsers/xml_parser.rb~
krikri-0.11.2 lib/krikri/parsers/xml_parser.rb~
krikri-0.11.1 lib/krikri/parsers/xml_parser.rb~
krikri-0.11.0 lib/krikri/parsers/xml_parser.rb~
krikri-0.10.1 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.9 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.8 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.7 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.6 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.5 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.4 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.2 lib/krikri/parsers/xml_parser.rb~
krikri-0.8.0 lib/krikri/parsers/xml_parser.rb~
krikri-0.7.3 lib/krikri/parsers/xml_parser.rb~
krikri-0.7.2 lib/krikri/parsers/xml_parser.rb~
krikri-0.7.1 lib/krikri/parsers/xml_parser.rb~
krikri-0.6.0 lib/krikri/parsers/xml_parser.rb~