I am trying to learn how to use Nokogiri and parse XML files, however I can't seem to get past this issue I am having.
I have this XML file with information about countries such as population, name, religion, inflation etc.:
<cia>
<continent id='europe'
name='Europe'/>
<continent id='asia'
name='Asia'/>
<continent id='northAmerica'
name='North America'/>
<continent id='australia'
name='Australia/Oceania'/>
<continent id='southAmerica'
name='South America'/>
<continent id='africa'
name='Africa'/>
<country id='cid-cia-Albania'
continent='Europe'
name='Albania'
datacode='AL'
total_area='28750'
population='3249136'
population_growth='1.34'
infant_mortality='49.2'
gdp_agri='55'
inflation='16'
gdp_total='4100'
indep_date='28 11 1912'
government='emerging democracy'
capital='Tirane'>
<ethnicgroups name='Greeks'>3</ethnicgroups>
<ethnicgroups name='Albanian'>95</ethnicgroups>
<religions name='Muslim'>70</religions>
<religions name='Roman Catholic'>10</religions>
<religions name='Albanian Orthodox'>20</religions>
<borders country='cid-cia-Greece'>282</borders>
<borders country='cid-cia-Macedonia'>151</borders>
<borders country='cid-cia-Serbia-and-Montenegro'>287</borders>
<coasts>Adriatic Sea</coasts>
<coasts>Ionian Sea</coasts>
<coasts>Serbia</coasts>
<coasts>Montenegro</coasts>
</country>
.
.
.
</cia>
I am trying to find a country by passing in the name of the country as an argument, and, from there, trying to get the population of the country, but I can't for some reason. Here is my method:
@doc = Nokogiri::XML(File.read(file)) # get the file from the initialize method
def get_population(country)
element = @doc.xpath("//country[@name='#{country}']")
end
So if I do:
get_population('Albania')
How can I get this method to get the population for Albania? Currently all I get is the XML for that country.
Thanks for all the help in advance!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…