Sha256: 8484dc6b3d22f371b1c5b4341e354ac5918a37ce110ec3dedb43c406cd830000

Contents?: true

Size: 1.32 KB

Versions: 8

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

require 'active_support/inflector'
require 'nokogiri'

module HS
  module XMLParser
    def parse_xml(xml)
      doc = Nokogiri::XML(xml) do |config|
        config.options = Nokogiri::XML::ParseOptions::STRICT
      end

      to_object_notation(doc.root)
    end

    # Text content of the node.
    # Note, that we don't go deep into element tree.
    def get_text(object)
      object[:_children].map { |obj| obj[:text] }.compact.join(' ')
    end

    private

    def attributes_hash(xml)
      xml.attributes.map do |key, attr|
        [key.underscore.to_sym, attr.value]
      end.to_h
    end

    def to_object_notation(xml)
      class_name = xml.class.name.split('::').last.downcase
      send("#{class_name}_to_object_notation", xml)
    end

    def element_to_object_notation(xml)
      data = attributes_hash(xml)
      data[:_name] = xml.name.underscore.to_sym
      data[:_children] = to_object_notation(xml.children)

      data
    end

    def cdata_to_object_notation(xml)
      text_to_object_notation(xml)
    end

    def text_to_object_notation(xml)
      {
        _name: :text,
        text: xml.text
      }
    end

    def nodeset_to_object_notation(xml)
      xml.map { |node| to_object_notation(node) }.compact
    end

    def comment_to_object_notation(_xml)
      nil
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
hs-cli-0.3.3 lib/hs/loaders/xml_parser.rb
hs-cli-0.3.2 lib/hs/loaders/xml_parser.rb
hs-cli-0.3.1 lib/hs/loaders/xml_parser.rb
hs-cli-0.3.0 lib/hs/loaders/xml_parser.rb
hs-cli-0.2.2 lib/hs/loaders/xml_parser.rb
hs-cli-0.2.1 lib/hs/loaders/xml_parser.rb
hs-cli-0.2.0 lib/hs/loaders/xml_parser.rb
hs-cli-0.1.2 lib/hs/loaders/xml_parser.rb