0

I am making the following request:

  uri = URI.parse(url)
  session = Net::HTTP.new(uri.host, uri.port)
  headers = {}
  res = session.start do |http|
    http.get(request_url, headers)
  end

Response looks like this:

<string xmlns="http://xxx">
    some string
</string>

Is there some fast solution to parse the above response and get that some string. I can get it using a regexp but I would like use something which exists in Ruby.

1
  • Use.. Nokogiri to parse res. Commented Jul 25, 2014 at 12:55

3 Answers 3

1

Use any XML parser. For example, nokogiri:

require 'nokogiri'
n = Nokogiri::HTML::parse response
parsed_string = n.xpath('//string').text
Sign up to request clarification or add additional context in comments.

Comments

1

As Arup Rakshit commented, use nokogiri to parse the xml:

require 'nokogiri'

res = <<EOS
<string xmlns="http://xxx">
    some string
</string>
EOS

root = Nokogiri.parse(res)
root.at_xpath('.//*[local-name()="string"]').text.strip  # Using xpath
# => "some string"
root.at_css('string').text.strip  # Using css selector
# => "some string"

Comments

0

You can parse that XML using REXML or SimpleXML, and get the string.

I prefer SimpleXML.

Sample

data['Result'].each do |item|
   item.sort.each do |k, v|
      if ["Title", "Url"].include? k
         print "#{v[0]}" if k=="Title"
         print " => #{v[0]}\n" if k=="Url"
      end
   end
end

https://developer.yahoo.com/ruby/ruby-xml.html

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.