Sha256: 0de89975cf28d69f892eff6e173eea4f58af752b251266df1b0de696dceb3677

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

require 'nokogiri'

# Really simple XML parsing.
module Crackr
  module XML
    # Builds a hash from an XML document.
    #
    # @param [Nokogiri::XML::Document, Nokogiri::XML::Element, String] xml A
    # Nokogiri XML document, an element thereof, or a string representation of
    # an XML document.
    # @return [Hash]
    def self.parse(xml)
      case xml
      when String
        parse Nokogiri::XML(xml)
      when Nokogiri::XML::Document
        parse xml.root
      when Nokogiri::XML::Element
        hsh = {}

        xml.attributes.each_pair do |key, attribute|
          hsh[key] = attribute.value
        end

        xml.children.each do |child|
          result = parse child

          if child.name == 'text'
            if hsh.empty?
              return result
            else
              hsh['__content__'] = result
            end
          elsif hsh[child.name]
            case hsh[child.name]
            when Array
              hsh[child.name] << result
            else
              hsh[child.name] = [hsh[child.name]] << result
            end
          else
            hsh[child.name] = result
          end
        end

        hsh
      else
        xml.content.to_s
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
crackr-1.0.0 lib/crackr/xml.rb