加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Happymapper(fork) – 来自多个类的输出

发布时间:2020-12-16 21:07:13 所属栏目:百科 来源:网络整理
导读:我的问题涉及基于 https://github.com/dam5s/happymapper的文档创建输出,这是使用nokogiri的happymapper的分支. 我在使用文档时使用了两个例子.这是我的榜样. xml_doc = EOFaddress location='home' streetMilchstrasse/street streetAnother Street/street
我的问题涉及基于 https://github.com/dam5s/happymapper的文档创建输出,这是使用nokogiri的happymapper的分支.

我在使用文档时使用了两个例子.这是我的榜样.

xml_doc = <<EOF
<address location='home'>
  <street>Milchstrasse</street>
  <street>Another Street</street>
  <housenumber>23</housenumber>
  <postcode>26131</postcode>
  <city>Oldenburg</city>
  <country code="de">Germany</country>
</address>
EOF

class Address
  include HappyMapper

  tag 'address'

  element :housenumber,Integer,:tag => "housenumber"
end

class Country
  include HappyMapper

  tag 'country'

  attribute :code,String
  content :name,String

end

outputs = Country.parse(xml_doc)
outputs.each do |output|
  puts output.code
  puts output.name
  puts output.housenumber
end

预期产出

de
Germany
23

我的输出

sayth@sayth-E6410 ~/race (master●)$ruby read_race.rb            [ruby-2.4.0p0]
de
Germany
read_race.rb:49:in `block in <main>': undefined method `housenumber' for #<Country:0x0055e55facf798 @code="de",@name="Germany"> (NoMethodError)
    from read_race.rb:46:in `each'
    from read_race.rb:46:in `<main>'

解决方法

这或多或少是从文档直接复制/粘贴.我希望它能满足你的需求.

最重要的部分是调用Address.parse而不是Country.parse,并将Country字段称为output.country.code而不是output.code.然后它的工作原理与Happymapper的自述文件完全一样.

#!/usr/bin/env ruby

require 'happymapper'

ADDRESS_XML_DATA = <<XML
<root>
    <address location='home'>
      <street>Milchstrasse</street>
      <street>Another Street</street>
      <housenumber>23</housenumber>
      <postcode>26131</postcode>
      <city>Oldenburg</city>
      <country code="de">Germany</country>
    </address>
</root>
XML

class Country
  include HappyMapper

  tag 'country'

  attribute :code,String
  content   :name,String
end

class Address
  include HappyMapper

  tag 'address'

  has_many :streets,String,:tag => 'street'

  def streets
    @streets.join('n')
  end

  element :postcode,:tag => 'postcode'
  element :housenumber,:tag => 'housenumber'
  element :city,:tag => 'city'
  element :country,Country,:tag => 'country'
end

outputs = Address.parse(ADDRESS_XML_DATA)
outputs.each do |output|
  puts output.country.code
  puts output.country.name
  puts output.housenumber
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读