简体   繁体   English

Ruby on Rails-需要将XML文件读入数组

[英]Ruby on Rails - Need to Read XML File into an Array

I am using Ruby on Rails and need to read the contents of an xml file into an array? 我正在使用Ruby on Rails,需要将xml文件的内容读入数组吗?

I pulled the data from an API using the following: 我使用以下方法从API中提取了数据:

     uri = URI.parse("myAPIurl.com&show=storeID,name")
    http = Net::HTTP.new(uri.host, uri.port)
 request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)

Looking for a lean method to iterate this xml file into an array using Ruby on Rails. 寻找一种精益方法使用Ruby on Rails将这个xml文件迭代到一个数组中。

For simple use cases you can use: 对于简单的用例,您可以使用:

xml = <<-XML
  <?xml version="1.0" encoding="UTF-8"?>
    <hash>
      <foo type="integer">1</foo>
      <bar type="integer">2</bar>
    </hash>
XML

hash = Hash.from_xml(xml)
# => {"hash"=>{"foo"=>1, "bar"=>2}}

Hash - Ruby on Rails 哈希-Ruby on Rails

Try using Nokogiri gem. 尝试使用Nokogiri宝石。 It's super easy to use, the website has some nice examples. 它非常易于使用,网站上有一些很好的例子。

require 'open-uri'
doc = Nokogiri::HTML(open("myAPIurl.com&show=storeID,name"))

you can then query your document using xpath or css selectors. 然后,您可以使用xpath或CSS选择器查询文档。 It then returns a NodeSet that you can iterate over like you would do with an array 然后,它返回一个NodeSet,您可以像对数组那样进行迭代

Hope it helps 希望能帮助到你

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

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