简体   繁体   中英

How do I convert an XML file for use in a Rails application?

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:

  1. Reading the XML file into your program
  2. Converting the XML into a hash, or any other suggestion

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

now you can access the value in xml by

doc.xpath('tag name')

for the text value

doc.xpath('tag name').text

EXAMPLE

To print name and id

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM