Tag Archives: rails console

Export XML file from rails console

One of my last project I need to export XML file for automate a data entry. I follow those simple steps to generate XML file from rails console.

Here is my script to generate XML file:

require 'builder'
@schools = School.where(state_code: 'NV').order('name DESC')
    file = File.new("#{Rails.root}/public/data.xml", 'w')

    xml = Builder::XmlMarkup.new(target: file, :indent => 2)
    xml.instruct! :xml, :version=>'1.0'

    xml.tag! 'plist' , 'version' => '1.0' do
      xml.array do
        @schools.each do |s|
          xml.dict do
            xml.key 'id'
            xml.string s.id
            xml.key 'name'
            xml.string s.name
            xml.key 'zip'
            xml.string s.zipcode
          end
        end
      end
    end

Happy coding 🙂