Currently, I have an XML document (called Food_Display_Table.xml) with data in a format like this:
<Food_Display_Table>
<Food_Display_Row>
<Food_Code>12350000</Food_Code>
<Display_Name>Sour cream dip</Display_Name>
....
<Solid_Fats>105.64850</Solid_Fats>
<Added_Sugars>1.57001</Added_Sugars>
<Alcohol>.00000</Alcohol>
<Calories>133.65000</Calories>
<Saturated_Fats>7.36898</Saturated_Fats>
</Food_Display_Row>
...
</Food_Display_Table>
I would like to print some of this information in human readable format. Like this:
-----
Sour cream dip
Calories: 133.65000
Saturated Fats: 7.36898
-----
So far, I have tried this, but it doesn’t work:
require 'rexml/document'
include REXML
data = Document.new File.new("Food_Display_Table.xml", "r")
data.elements.each("*/*/*") do |foodcode, displayname, portiondefault, portionamount, portiondisplayname, factor, increments, multiplier, grains, wholegrains, orangevegetables, darkgreenvegetables, starchyvegetables, othervegetables, fruits, milk, meats, soy, drybeans, oils, solidfats, addedsugars, alcohol, calories, saturatedfats|
puts "----"
puts displayname
puts "Calories: {calories}"
puts "Saturated Fats: {saturatedfats}"
puts "----"
end
Use Xpath. I tend to go with Nokogiri as I prefer the API.
With the paths hard-coded:
or for something a bit DRYer.