Sha256: ac265ca30f503f8fa307664293d6ca2697bf0e202b6c33063d0b585bc919aa62

Contents?: true

Size: 1.21 KB

Versions: 4

Compression:

Stored size: 1.21 KB

Contents

module CiviCrm
  class XML
    class << self
      def parse(text)
        # CiviCRM <Result>s sometimes contain invalid elements
        # like <preferred_communication_method><0></0></ ...
        # Get rid of them before parsing.
        fixed_text = text.to_s.
                     gsub("\n", "").
                     gsub(/<\d+>(.*?)<\/\d+>/, "")

        doc = Nokogiri::XML.parse(fixed_text)

        results = doc.xpath('//Result')
        results.map do |result|
          hash = {}
          result.children.each do |attribute|
            next unless attribute.is_a?(Nokogiri::XML::Element)
            hash[attribute.name] = attribute.children[0].text rescue nil
          end
          hash
        end
      end
      def encode(resources)
        builder = Nokogiri::XML::Builder.new do |xml|
          xml.ResultSet do
            Array.wrap(resources).each do |resource|
              attributes = resource.respond_to?(:attributes) ? resource.attributes : resource
              xml.Result do
                attributes.each do |key, value|
                  xml.send key.to_sym, value
                end
              end
            end
          end
        end
        builder.to_xml
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
civicrm-1.1.1 lib/civicrm/xml.rb
civicrm-1.1.0 lib/civicrm/xml.rb
civicrm-1.0.7 lib/civicrm/xml.rb
civicrm-1.0.6 lib/civicrm/xml.rb