Search code examples
ruby-on-railsxmlrexml

Parse xml file with rails REXML?


How can i parse this xml file ?

<resultset>
−<row>
<field name="Table Name">table_1</field>
<field name="Quant of Rows">2</field>
<field name="Total Size Mb">0.02</field>
</row>
−<row>
<field name="Table Name">table_2</field>
<field name="Quant of Rows">1</field>
<field name="Total Size Mb">0.02</field>
</row>
</resultset>

I am using REXML.


Solution

  •     table_data = []
        xml = File.read('file1.xml')
        doc, posts = REXML::Document.new(xml), []
        doc.elements.each('resultset/row') do |table_row|
          table_data << {:table_name => table_row.elements[1].text,
            :record_count => table_row.elements[2].text,
            :size_in_mb => table_row.elements[3].text
          }
        end