Question

I am trying to read an XML file and store the structure into an array of objects. Here is my code:

class Bike
    attr_accessor :id, :color, :name
    def initialize(id, color, name)
        @id = id
        @color = color
        @name = name
    end
end

---x---snip---x---

rules.root.each_element do |node1|
    case node1.name
    when "Bike"
        bike = Bike.new(node1.attributes['id'], node1.attributes['color'], { |bike_elem| bike_elem.text.chomp if bike_elem.name == "name"})
        bikes.push bike
    end
end

However, the last element is not fetching the value alone. It is fetching the whole tag. Is there a better way to do it?

Was it helpful?

Solution

Your code block { |bike_elem| bike_elem.text.chomp if bike_elem.name == "name" } doesn't seem to make sense inside the new parameter list.

Where does bike_elem come from? This is not valid Ruby in this context.

It's hard to give an answer here without knowing what your XML looks like. But I would recommend using a XML library like Nokogiri, libxml, and then parse out the name before you do the new. Try using XPath.

 rules.root.each_element do |node1|
  case node1.name
    when "Bike"
      name = node1.attributes[....]
      bike = Bike.new(node1.attributes['id'], node1.attributes['color'],name )
      bikes.push bike
    end
 end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top