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