1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.