class Xapper::Mapper

Attributes

mappings[RW]
namespaces[RW]

Public Instance Methods

map(xml_str) click to toggle source
# File lib/xapper.rb, line 23
def map(xml_str)
  xml  = Nokogiri::XML(xml_str)
  map_xml_data(xml, @mappings, {})
end

Protected Instance Methods

map_xml_data(xml, mappings, data) click to toggle source
# File lib/xapper.rb, line 30
def map_xml_data(xml, mappings, data)

  mappings.each_pair do |key, val|

    # We have a proc object
    if val.is_a? Proc
      data[key] = val.call xml
      next
    end

    # Recurse on hash
    if val.is_a? Hash
      data[key] = map_xml_data(xml, val, {})
      next
    end

    if val.is_a? Array
      xpath = val[0]
      submap = val[1]
      items = xml.xpath(xpath, @namespaces)
      data[key] = items.map {|node| map_xml_data(node, submap, {})}
      next
    end

    # We have an xpath to lookup
    node      = xml.xpath(val,@namespaces)[0]

    if node.class == Nokogiri::XML::Element
      data[key] = node.content
    elsif node.class == Nokogiri::XML::Attr
      data[key] = node.value
    else
      data[key] = nil
    end

  end

  data

end