views:

108

answers:

1

Just getting started with Ruby and have a newbie question re parsing XML. I'm trying REXML (yes, I know hpricot and others exist, but I am starting with REXML to learn.) The problem is how to iteratively proceed through a XML doc like this:

<?xml version="1.0" ?>
<bars>
    <bar>
     <id>29</id>
     <foo>Something</foo>
    </bar>
    <bar>
     <id>46</id>
     <foo>Something Else</foo>
    </bar>
    ...
</bars>

I'd like to process both elements within each "bar" at the same time (dropping both fields into a database row in one operation, actually), rather than simply plucking out all the "ids" or "foos" at once across all "bars" as is often shown in tutorials. What is the best way to iterate over thru the "bar" elements? Should I .each within "bars" or should I convert the structure to arrays?

+1  A: 

Assuming Bar is an ActiveRecord model this is what you want to do.

require "rexml/document"
include REXML
root = Document.new(File.new(file)).root

root.elements.each("bar") do |bar|
  id = bar.elements["id"].text
  foo = bar.elements["foo"].text
  Bar.create (:id => id, :foo => foo)
end

Essentially it gets a list of Bar elements, and then just pulls id and foo into a Bar.create statement for each bar element in that list.

EmFi