0

How do I save the information from an XML page that I got from a API?

The URL is "http://api.url.com?number=8-6785503" and it returns:

<OperatorDataContract xmlns="http://psgi.pts.se/PTS_Number_Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Tele2 Sverige AB</Name>
  <Number>8-6785503</Number>
</OperatorDataContract>

How do I parse the Name and Number nodes to a file?

Here is my code:

require 'rubygems'
require 'nokogiri'
require 'open-uri'


url = "http://api.url.com?number=8-6785503"
doc = Nokogiri::XML(open(url))

File.open("exporterad.txt", "w") do |file|
            doc.xpath("//*").each do |item|
                title = item.xpath('//result[group_name="Name"]')

                phone = item.xpath("/Number").text.strip


                puts "#{title} ; \n"
                puts "#{phone} ; \n"




                company = " #{title}; #{phone}; \n\n"

                file.write(company.gsub(/^\s+/,''))



        end

end
Cyrus Zei
  • 2,589
  • 1
  • 27
  • 37

1 Answers1

1

Besides the fact that your code isn't valid Ruby, you're making it a lot harder than necessary, at least for a simple scrape and save:

require 'nokogiri'
require 'open-uri'

url = "http://api.pts.se/PTSNumberService/Pts_Number_Service.svc/pox/SearchByNumber?number=8-6785503"
doc = Nokogiri::XML(open(url))

File.open("exported.txt", "w") do |file|
  name = doc.at('Name').text
  number = doc.at('Number').text
  file.puts name
  file.puts number
end

Running that results in a file called "exported.txt" that contains:

Tele2 Sverige AB
8-6785503

You can build upon that as necessary.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • Glad it helped. Dealing with HTML, XHTML and XML can be frustrating, especially with XML with namespaces. Nokogiri provides a lot of features that make it easier to navigate and locate what you want. One of those is its ability to use CSS to select nodes, rather than XPath. While XPath is more capable, it's also more complex, so I start with CSS for readability and then switch to XPath if I have to. Others are more familiar with it so they use it only. That's the beauty of Nokogiri though, is it allows us to make those choices. – the Tin Man Oct 14 '14 at 16:04
  • I will look into the css selector and learn that. I wounder if you could maybe look at my other problem that I have. I dont understand the logic when it comes to passing a value from on table in to a variable. [link]http://stackoverflow.com/questions/26389455/how-to-iterate-through-all-records-and-pass-database-value-to-a-variable am I thinking right or I have missed something here ? – Cyrus Zei Oct 16 '14 at 06:52
  • Hi again, Sorry to bouther you "The Tin Man", but I am going blind on this and I dont know why I dont get it to work at all here. What am I doing wrong ? http://stackoverflow.com/questions/26689914/ruby-on-rails-import-csv-from-upload-file-to-active-records-using-smarter-csv – Cyrus Zei Nov 02 '14 at 18:40