Giter Club home page Giter Club logo

ox-mapper's Introduction

Ox::Mapper

Ox::Mapper's intention is to simplify creation of parsers based on ox

Installation

Add this line to your application's Gemfile:

gem 'ox-mapper'

And then execute:

$ bundle

Or install it yourself as:

$ gem install ox-mapper

Usage

All you need to do is to setup callbacks for elements and attributes in Ruby style

mapper = Ox::Mapper.new

mapper.on(:book) { |book| puts book.attributes.inspect }
mapper.on(:title) { |title| title.parent[:title] = title.text }

# collected attributes should be set up explicitely
mapper.on(:author, :attributes => :name) { |e| e.parent[:author] = e[:name] }

# setup transformation for attribute "value" of "price" element
mapper.on(:price, :attributes => :value) { |e| e.parent[:price] = Float(e[:value]) }

mapper.parse(StringIO.new <<-XML) # => {:title => "Serenity", :author => "John Dow", :price => 1123.0}
  <xml>
    <book>
      <title>Serenity</title>
      <author name="John Dow" age="99" />
      <price value="1123" />
    </book>
  </xml>
XML

This API is unstable and a subject to change.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

ox-mapper's People

Contributors

take-five avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

xrustq

ox-mapper's Issues

get updated xml back?

Using your example code in the readme, how would you get the now updated xml back?

p.s. thank you for this lib!

Новый DSL (обсуждение)

Предположим, у нас есть XML-документ следующей структуры:

<?xml version="1.0" encoding="utf-8"?>
<shop>
  <categories>
    <category id="1">Electronics</category>
    <category id="2" parentId="1">Phones</category>
  </categories>

  <offers>
    <offer id="1" available="true">
      <name>iPhone 5</name>
      <categoryId>2</categoryId>
      <price currencyId="RUR">25000</price>
      <params>
        <param name="Color">White</param>
        <param name="Battery">2000 mA/h</param>
      </params>
    </offer>

    <offer>...</offer>
  </offers>
</shop>

Предлагается следующее API для создания парсера документа такой структуры:

parser = Ox::Mapper.document do
  # map означает, что по элементам с таким именем будет производиться итерация
  # :scope => :categories означает, что итерация будет производиться только по элементам
  # <category>, которые находятся внутри элементов <categories>
  map :category, :scope => :categories do
    # из элемента category мы берем атрибуты id и parentId, причем ко второму можно будет обратиться по имени parent_id
    attributes :id, :parentId => :parent_id
  end

  # :scope => '/shop/offers' означает, что итерация будет производиться только по элементам <offer>,
  # вложенным в элемент <offers>, вложенный в элемент <shop>, являющимся корневым
  map :offer, :scope => '/shop/offers' do
    attribute :id
    attribute :available

    # element_value означает, что из элемента <name> мы берем только его текст. к этому значению можно будет обратиться так - element[:name]
    element_value :name
    element_value :categoryId, :as => :category_id
    element :price do
      attribute :currencyId, :as => :currency_id
    end

    # множество однотипных элементов можно отобразить в коллекцию (массив)
    collection :params do
      element :param, :attributes => :name
    end
  end
end

parser.parse(STDIN) do |tag|
  case tag.name
    when :category
      p [tag.name, tag[:id], tag[:parent_id]]

    when :offer
      p [
        tag[:id],
        tag[:available],
        tag[:name],
        tag[:category_id],
        tag[:price][:currency_id], # вот это меня смущает
        tag[:price].text, # и это тоже
        tag[:params][0][:name],
        tag[:params][0].text,
        tag[:params][1][:name],
        tag[:params][1].text
      ]
  end
end

Очень приветствуются замечания и дополнения.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.