module Cardflex module Xml module Parser require 'rexml/document' unless defined? REXML::Document def self.xml_to_hash(xml) return {} if xml.nil? document = REXML::Document.new(xml) { _snakecase(document.root.name) => _parse_children(document.root) } end def self._parse_children(elem) if elem.has_elements? children = {} elem.each_element do |child| children[_snakecase(child.name)] = _parse_children(child) end children else elem.text end end def self._snakecase(key) key.tr('-', '_').to_sym end def self.parse(string) return {} if string.nil? doc = REXML::Document.new(string) { _snakecase(doc.root.name).to_sym => _to_hash({}, doc.root) } end def self._to_hash(hash, element) if element.has_elements? element.each_element do |child| hash[_snakecase(child.name).to_sym] = child.text end end hash end end end end