xml_mapper

Declarative mapping of XML files to ruby attributes

Example XML

<album>
  <title>Black on Both Sides</title>
  <version_title>Extended Edition</version_title>
  <released_in>1999</released_in>
  <released_on>1999-10-12</released_on>
  <country>de</country>
  <allows_streaming>true</allows_streaming>
  <artist>
    <name>Mos Def</name>
    <id>1212</id>
  </artist>
  <contributions>
    <artist>Mos Def</artist>
    <producer>DJ Premier</producer>
  </contributions>
  <tracks>
    <track code="1234">
      <title>Fear Not of Man</title>
      <version_title></version_title>
      <number>1</number>
      <disk>1</number>
      <explicit_lyrics />
      <not_streamable_in>
        <country>de</country>
      </not_streamable_in>
    </track>
    <track code="2345">
      <title>Hip Hop</title>
      <version_title>Album Version</version_title>
      <number>2</number>
      <disk>1</number>
      <performer>Mos Def</performer>
      <producer>DJ Premier</producer>
      <not_streamable_in>
        <country>at</country>
      </not_streamable_in>
    </track>
  </tracks>
</album>

Example Mapper

require "xml_mapper"
require "date"

class MyMapper < XmlMapper
  text :title, :version_title                             # 1:1 - maps xpaths title and version_title to attribute keys
  integer :released_in                                    # converts value to an integer
  text :country, :after_map => :upcase                    # calls after_map method on extracted value if value responds to the method
  text :released_on, :after_map => :parse_date            # calls after_map method defined in Mapper class when value does not respond
  boolean :allows_streaming                               # maps 1, Y, y, yes, true => true, 0, N, n, no, false => false

  within :artist do
    text :name => :artist_name                            # adds mapping for xpath "artist/name"
    integer :id => :artist_id
  end

  many "contributions/*" => :contributions do             # use the name of xml nodes for mappings
    node_name :role                                       # map name of xml node to :role
    inner_text :name                                      # map inner_text of xml node to :name
  end

  many "tracks/track" => :tracks do                       # maps xpath "tracks/track" to array with key :tracks
    attribute :code => :isrc                              # map xml attribute "code" to :isrc
    text :title => :track_title
    text :version_title
    integer :number => :track_number
    integer :disk => :disk_number
    exists :explicit_lyrics                               # checks if a node with the xpath exists
    not_exists "not_streamable_in/country[text()='de']" => :allows_streaming

    text :performer => { :contributions => :performer }   # assigns to content at xpath :performer to attributes[:contributions][:performer]
    text :producer => { :contributions => :producer }     # assigns to content at xpath :performer to attributes[:contributions][:producer]
  end

  after_map do                                                    # is called after attributes are extracted, self references the extracted attributes
    self[:tracks_count] = self[:tracks].length
    self[:xml_path] = self.xml_path                               # lets you access the xml_path when called with attributes_from_xml_path
    self[:other_tracks_count] = self.node.search("track").count   # lets you access the current xml node (in this case the whole doc)
  end

  # to be used for after_map callbacks
  def parse_date(date_string)
    Date.parse(date_string)
  end
end

How to call

  • MyMapper.attributes_from_xml(xml)

  • MyMapper.attributes_from_xml_path(xml)

Output

{
  :title=>"Black on Both Sides", :allows_streaming=>true, :version_title=>"Extended Edition", 
  :tracks=>[
    { :track_title=>"Fear Not of Man", :allows_streaming=>false, :track_number=>1, :version_title=>nil, :disk_number=>1, 
      :explicit_lyrics=>true, :contributions=>{:performer=>nil, :producer=>nil}, :isrc=>"1234"
    }, 
    { :track_title=>"Hip Hop", :allows_streaming=>true, :track_number=>2, :version_title=>"Album Version", :disk_number=>1, 
      :explicit_lyrics=>false, :contributions=>{:performer=>"Mos Def", :producer=>"DJ Premier"}, :isrc=>"2345"
    }
  ], 
  :tracks_count=>2, :released_in=>1999, 
  :released_on=>#<Date: 4902927/2,0,2299161>, :artist_name=>"Mos Def", 
  :contributions=>[ {:name=>"Mos Def", :role=>"artist"}, {:name=>"DJ Premier", :role=>"producer"} ]
  :artist_id=>1212, :country=>"DE"
}

Contributing to xml_mapper

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it

  • Fork the project

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright © 2010 Tobias Schwab (Dynport GmbH).

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.