This is an implementation example when you want to read the XML file uploaded from the screen in Hash type in the application using Rails (5 series).
This time I use the following XML file for verification
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item>AAA</item>
<item>BBB</item>
<item>CCC</item>
</items>
Place the file and button tag appropriately. (You can choose your design style!)
<%= form_tag xxx_path, multipart: true do %>
<label>Read XML file</label>
<div class="row">
<div class="col-sm-2">
<%= file_field_tag :file, class: 'btn btn-primary' %>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<%= submit_tag 'Send', class: 'btn btn-primary' %>
</div>
</div>
<% end %>
xml = REXML::Document.new(File.new(params[:file].path).read)
xml_h = Hash.from_xml(xml.to_s)
As a result of the above, you can get the contents of the file in Hash format as shown below.
{"items"=>{"item"=>["AAA", "BBB", "CCC"]}}
Recommended Posts