简体   繁体   English

如何转换XML文件以在Rails应用程序中使用?

[英]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. 我试图加载XML文件以适合Rails应用程序,但收效甚微。

I am thinking that I should use Nokogiri to parse the data. 我认为我应该使用Nokogiri来解析数据。 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. 这里的最终目标是从上面的链接,棒球统计数据中获取数据,并有一个表显示其数据,棒球运动员统计数据,并将其放入Rails应用程序中。

Basically, it's two parts: 基本上,它分为两个部分:

  1. Reading the XML file into your program 将XML文件读入程序
  2. Converting the XML into a hash, or any other suggestion 将XML转换为哈希或任何其他建议

I am using Rails 4.0, Ruby 2.0, on Mac OSX. 我在Mac OSX上使用Rails 4.0,Ruby 2.0。

How do I read the XML file and convert the data to allow it to run in a Rails application? 如何读取XML文件并转换数据以使其在Rails应用程序中运行?

I would use Nokogiri for this task. 我会用Nokogiri来完成这项任务。 Take a look at Ryan Bates RailsCasts " Screen Scraping with Nokogiri ". 看看Ryan Bates RailsCasts的“ Nokogiri 屏幕抓取 ”。

In case of XML it will look very similar, just use Nokogiri::XML in place of Nokogiri::HTML . 如果是XML,它将看起来非常相似,只需使用Nokogiri::XML代替Nokogiri::HTML Check the Nokogiri documentation - read the main page carefully. 查看Nokogiri文档 -仔细阅读主页。

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 现在您可以通过以下方式访问xml中的值

doc.xpath('tag name') doc.xpath('标签名称')

for the text value 文字值

doc.xpath('tag name').text doc.xpath('标记名称').text

EXAMPLE

To print name and id 打印名称和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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