Sha256: 6064c1ae3be61fd72036491187568b1f1502c31dc7770fabdeabc95c651bfe65

Contents?: true

Size: 1.28 KB

Versions: 3

Compression:

Stored size: 1.28 KB

Contents

# typed: true
# frozen_string_literal: true

require 'nokogiri'

module Workato
  module Connector
    module Sdk
      module Xml
        def self.parse_xml_to_hash(payload, strip_namespaces: false)
          parse_options = Nokogiri::XML::ParseOptions.new.nonet
          lazy_reader = Nokogiri::XML::Reader(payload, nil, nil, parse_options).to_enum.lazy
          lazy_reader.each_with_object([{}]) do |node, ancestors|
            ancestors.shift while ancestors.count > node.depth + 1
            case node.node_type
            when Nokogiri::XML::Reader::TYPE_ELEMENT
              element = HashWithIndifferentAccess.new
              node.attributes&.each do |name, value|
                element["@#{strip_namespaces ? name[/(?:^xmlns:)?[^:]+$/] : name}"] = value
              end
              (ancestors.first[strip_namespaces ? node.name[/[^:]+$/] : node.name] ||= []).push(element)
              ancestors.unshift(element)
            when Nokogiri::XML::Reader::TYPE_TEXT, Nokogiri::XML::Reader::TYPE_CDATA
              element = ancestors.first
              if element.key?(:content!)
                element[:content!] += node.value
              else
                element[:content!] = node.value
              end
            end
          end.last
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
workato-connector-sdk-1.0.3 lib/workato/connector/sdk/xml.rb
workato-connector-sdk-1.1.0 lib/workato/connector/sdk/xml.rb
workato-connector-sdk-1.0.2 lib/workato/connector/sdk/xml.rb