简体   繁体   中英

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?

I pulled the data from an API using the following:

     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.

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

Try using Nokogiri gem. 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. It then returns a NodeSet that you can iterate over like you would do with an array

Hope it helps

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