Giter Club home page Giter Club logo

ox-mapper's Issues

Новый 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

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

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!

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.