jokham
jokham

Reputation: 265

How to get values in XML data using Nokogiri?

I'm using Nokogiri to parse XML data that I'm getting from the roar engine after I create a user. The XML looks like below:

<roar tick="135098427907">
  <facebook>
    <create_oauth status="ok">
      <auth_token>14802206136746256007</auth_token>
      <player_id>8957881063899628798</player_id>
    </create_oauth>
   </facebook>
</roar>

I'm totally new to Nokogiri. How do I get the value of status, the auth_token and player_id?

Upvotes: 1

Views: 279

Answers (3)

saihgala
saihgala

Reputation: 5774

You can use Nori gem. Its a xml to hash converter and in ruby its so much convenient to access hashes

require 'nori'

Nori.parser = :nokogiri

xml = "<roar tick='135098427907'>
           <facebook>
               <create_oauth status='ok'>
                   <auth_token>14802206136746256007</auth_token>
                   <player_id>8957881063899628798</player_id>
               </create_oauth>
           </facebook>
      </roar>"

hash = Nori.parse(xml)
create_oauth = hash["roar"]["facebook"]["create_oauth"]

puts create_oauth["auth_token"] # 14802206136746256007
puts create_oauth["@status"]    # ok
puts create_oauth["player_id"]  # 8957881063899628798

Upvotes: 2

halfelf
halfelf

Reputation: 10107

str = "<roar ......"
doc = Nokogiri.XML(str)
puts doc.xpath('//create_oauth/@status')  # => ok
puts doc.xpath('//auth_token').text       # => 148....
# player_id is the same as auth_token

And it is a great idea to learn you some good xpath from w3schools.

Upvotes: 2

Viren
Viren

Reputation: 5962

How about this

h1 = Nokogiri::XML.parse %{
    <roar tick="135098427907">
  <facebook>
    <create_oauth status="ok">
      <auth_token>14802206136746256007</auth_token>
      <player_id>8957881063899628798</player_id>
    </create_oauth>
   </facebook>
</roar>
}


h1.xpath("//facebook/create_oauth/auth_token").text()
h1.xpath("//facebook/create_oauth/player_id").text()

Upvotes: 2

Related Questions