gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:17:31 25 4
gpt4 key购买 nike

我的问题与根据 https://github.com/dam5s/happymapper 上的文档创建输出有关这是使用 nokogiri 的 happymapper 的分支。

我已经使用了 2 个示例来处理文档。这是我的例子。

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 字段作为 输出。 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 , String , :tag => 'postcode'
element :housenumber, String , :tag => 'housenumber'
element :city , String , :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

关于ruby - Happymapper(fork) - 来自多个类的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com