I am trying to load an XML file to fit into a Rails application and am having very little success.
I am thinking that I should use Nokogiri to parse the data. The end goal here is to take the data from the link above, baseball stats, and have a table displaying its data, the baseball players stats and fit this into a Rails application.
Basically, it's two parts:
I am using Rails 4.0, Ruby 2.0, on Mac OSX.
How do I read the XML file and convert the data to allow it to run in a Rails application?
I would use Nokogiri for this task. Take a look at Ryan Bates RailsCasts " Screen Scraping with Nokogiri ".
In case of XML it will look very similar, just use Nokogiri::XML
in place of Nokogiri::HTML
. Check the Nokogiri documentation - read the main page carefully.
require 'nokogiri' #You need nokogiri gem
doc = Nokogiri::XML(File.open("file_name.xml")) #Open your xml file
doc.xpath('tag name')
doc.xpath('tag name').text
EXAMPLE
xml_str = <<EOF
<root>
<thing>
<id>1234</id>
<name>The Name1</name>
</thing>
<thing>
<id>2234</id>
<name>The Name2</name>
</thing>
</root>
EOF
doc = Nokogiri::XML(xml_str)
doc.xpath('root').xpath('thing').each do |v|
puts v.xpath('id').text
puts v.xpath('name').text
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.