我的问题涉及根据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>'
答案 0 :(得分:3)
这或多或少是从文档直接复制/粘贴。我希望它能为你提供你想要的东西。
最重要的部分是调用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 , 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